Full Schema Stitching with Apollo Server
转自: https://tomasalabes.me/blog/nodejs/graphql/apollo/2018/09/18/schema-stitiching-apollo.html
Full Schema Stitching with Apollo Server
In this post we will see how we can stitch the queries/mutations and subscriptions from an Apollo Server and its Links packages. Plus a few tips to make it more interesting ;)
Our Goal
Our goal is creating a single apollo-link
that will let Apollo stitch all requests going to the server and send them to the right downstream server.
apollo-stitching
Once we have the function that creates the link, the overall code should look something like this:
import { introspectSchema, makeRemoteExecutableSchema, mergeSchemas } from 'graphql-tools';
export const createSchema = async () => {
const { link } = createLink(); // -> this is the method that we will create
const introspectedSchema = await introspectSchema(link);
const schema = makeRemoteExecutableSchema({
link,
schema: introspectedSchema
});
return mergeSchemas({
schemas: [
schema
// more schemas
]
});
};
Ok, let’s stitch!
Mutations / Queries using “apollo-link-http”
This one is pretty straight forward, apollo-link-http redirects http/s queries to the provided URL. I use node-fetch
which is the recommended fetch
package for Node.
import { HttpLink } from 'apollo-link-http';
import fetch from 'node-fetch';
const createHttpLink = (gqlServerUrl) => {
const uri = `http://${gqlServerUrl}/graphql`;
return new HttpLink({
fetch,
uri
});
};
Subscriptions using “apollo-link-ws”
Now subscriptions. We need to use apollo-link-ws It’s similar to the http-link except we need to first create a SubscriptionClient where we pass the url, options and the websockets node implementation. In the previous link we passed the fetch implementation, now is the websocket’s one.
import WebSocket from 'ws';
import { WebSocketLink } from 'apollo-link-ws';
import { SubscriptionClient } from 'subscriptions-transport-ws';
import { WebSocketLink } from 'apollo-link-ws';
const createWsLink = (gqlServerUrl) => {
const wsUri = `ws://${gqlServerUrl}/subscriptions`;
const wsClient = new SubscriptionClient(
wsUri,
{
reconnect: true // if connection is lost, retry
},
WebSocket
);
return new WebSocketLink(wsClient);
};
All options for the SubscriptionClient
are here.
Creating the Link + a Retry Mechanism
This is where we add the “magic”. We will use the above 2 links, with a split and retry strategies.
We will:
- Create the HTTP and WS links
- Using split, depending on the requested operation we will evaluate what link is needed
- Using RetryLink, we will check if there was an error connecting to the server, and retry the connection if necessary
import { RetryLink } from 'apollo-link-retry';
import { getMainDefinition } from 'apollo-utilities';
const createLink = () => {
const projectGqlServer = `your-gql-server:3000`;
const httpLink = createHttpLink(projectGqlServer);
const wsLink = createWsLink(projectGqlServer);
const link = new RetryLink({
// these are the defaults, change them as you will
delay: {
initial: 300, // The number of milliseconds to wait before attempting the first retry.
max: Infinity, // The maximum number of milliseconds that the link should wait for any retry
jitter: true // Whether delays between attempts should be randomized.
},
attempts: {
max: 5, // The max number of times to try a single operation before giving up.
retryIf: (error, _operation) => !!error // A predicate function that can determine whether a particular response should be retried.
}
}).split( // using "Directional Composition" of links
({ query }) => {
const { kind, operation } = getMainDefinition(query);
return kind === 'OperationDefinition' && operation === 'subscription';
},
wsLink,
httpLink
);
return { link };
};
Conclusion
With this you should be able to route all types of operations received by this server to the remote server.
There’re other strategies using other link packages but I haven’t tried them, as some I think don’t apply to the server but to the client. But I think this gives you the base for the stitching, from here you can take it to where you need it.
As always, hope it helps! And share if it does!
Cheers!
Full Schema Stitching with Apollo Server的更多相关文章
- [Apollo Server] Get started with Apollo Server
Get started with apollo server with node.js: Install: npm install --save apollo-server graphql index ...
- GraphQL-- 使用Apollo Server搭建Node服务端
一.关于Apollo Server Apollo Server是一种使用JS创建GraphQL服务端的一个方案.它的兼容性比较好,可以很好地和GraphQL客户端进行兼容.同时它可以 独立作为服务端进 ...
- 转 GraphQL Schema Stitching explained: Schema Delegation
转自官方文档 In the last article, we discussed the ins and outs of remote (executable) schemas. These remo ...
- Apollo的基本概念和集成实战
基本概念 使用场景 是一个分布式的配置中心.适用于微服务: 核心功能 集中管理不同环境,不同集群的配置: 配置修改后可以实时推送到应用端: 具备规范的权限,流程治理特性: 开发技术 服务端使用spri ...
- SQL Server DML(UPDATE、INSERT、DELETE)常见用法(一)
1.引言 T-SQL(Transact Structured Query Language)是标准的SQL的扩展,是程序和SQL Server沟通的主要语言. T-SQL语言主要由以下几部分组成: 数 ...
- Oracle 迁移某用户的数据到Sql Server
准备条件: 1.Oracle11g数据库 2.Sql Server 2008 3.Microsoft SQL Server Migration Assistant for Oracle 步奏如下: 1 ...
- Confluence 6 SQL Server 创建一个数据库和数据库用户
一旦你成功安装了 SQL Server 服务器,请按照下面的方法为你的 Confluence 创建数据库用户和数据库: 使用你的 SQL 管理员权限,创建一个新的数据库(例如 confluence). ...
- Microsoft SQL Server Trace Flags
Complete list of Microsoft SQL Server trace flags (585 trace flags) REMEMBER: Be extremely careful w ...
- sql server 小技巧(7) 导出完整sql server 数据库成一个sql文件,包含表结构及数据
1. 右健数据库 –> Tasks –> Generate Scripts 2. 选择所有的表 3. 下一步,选择Advanded, Types of data to script ...
随机推荐
- Python数据分析中对重复值、缺失值、空格的处理
对重复值的处理 把数据结构中,行相同的数据只保留一行 函数语法: drop_duplicates() from pandas import read_csv df = read_csv(文件位置) n ...
- 3.4 C++名字隐藏
参数:http://www.weixueyuan.net/view/6361.html 总结: 如果派生类中新增一个成员变量,该成员变量与基类中的成员变量同名,则新增的成员变量就会遮蔽从基类中继承过来 ...
- SQL-1 选取表中某一属性最大值的所有信息 查找最晚入职员工的所有信息
题目描述 查找最晚入职员工的所有信息CREATE TABLE `employees` (`emp_no` int(11) NOT NULL,`birth_date` date NOT NULL,`fi ...
- 类的无参方法和Doc注释
一:Java Doc注释: 语法: /** *AccpSchool 类 *@author JadeBird *@version 1.0 2018/5/26 */ Java Doc是前Sun公司提供的一 ...
- MySQL:基础知识
基础知识 一.软件的生命周期 软件定义 软件开发 软件使用与维护 二.数据(Data) 1.定义 描述客观事物特征或性质的某种符号,经过数字化处理存储在计算机 2.数据独立性 物理独立性:指用户的应用 ...
- Linux:【解决】无法连接 MKS:套接字连接尝试次数太多正在放弃
[解决]无法连接 MKS:套接字连接尝试次数太多正在放弃 操作: 我的电脑 -> 右键 -> 管理 -> 服务和应用程序 -> 服务: 开启下面的服务: 服务启动成功后,重 ...
- C#窗体换肤
Form1.cs using System;using System.Collections.Generic;using System.ComponentModel;using System.Data ...
- git使用简明教程
1.自己在gitlab.XXX.com创建一个项目 点击右上角的"+"符号,创建新项目. 项目名:xxxtest 2.在master分支提交一个文件Readme.txt 文件内容: ...
- 字体图标Font Awesome 的使用
下载地址:http://fontawesome.dashgame.com/ 将下载下来的压缩包解压,然后解压,将下载的整个文件夹复制到你的项目中,在你需要用字体图标的html中引入“font-awes ...
- gcd和lcm模板
long long gcd(long long b,long long c)//计算最大公约数{ return c==0?b:gcd(c,b%c);} long long lcm(long long ...