转自: 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-fetchwhich 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 urloptions 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:

  1. Create the HTTP and WS links
  2. Using split, depending on the requested operation we will evaluate what link is needed
  3. 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的更多相关文章

  1. [Apollo Server] Get started with Apollo Server

    Get started with apollo server with node.js: Install: npm install --save apollo-server graphql index ...

  2. GraphQL-- 使用Apollo Server搭建Node服务端

    一.关于Apollo Server Apollo Server是一种使用JS创建GraphQL服务端的一个方案.它的兼容性比较好,可以很好地和GraphQL客户端进行兼容.同时它可以 独立作为服务端进 ...

  3. 转 GraphQL Schema Stitching explained: Schema Delegation

    转自官方文档 In the last article, we discussed the ins and outs of remote (executable) schemas. These remo ...

  4. Apollo的基本概念和集成实战

    基本概念 使用场景 是一个分布式的配置中心.适用于微服务: 核心功能 集中管理不同环境,不同集群的配置: 配置修改后可以实时推送到应用端: 具备规范的权限,流程治理特性: 开发技术 服务端使用spri ...

  5. SQL Server DML(UPDATE、INSERT、DELETE)常见用法(一)

    1.引言 T-SQL(Transact Structured Query Language)是标准的SQL的扩展,是程序和SQL Server沟通的主要语言. T-SQL语言主要由以下几部分组成: 数 ...

  6. Oracle 迁移某用户的数据到Sql Server

    准备条件: 1.Oracle11g数据库 2.Sql Server 2008 3.Microsoft SQL Server Migration Assistant for Oracle 步奏如下: 1 ...

  7. Confluence 6 SQL Server 创建一个数据库和数据库用户

    一旦你成功安装了 SQL Server 服务器,请按照下面的方法为你的 Confluence 创建数据库用户和数据库: 使用你的 SQL 管理员权限,创建一个新的数据库(例如 confluence). ...

  8. Microsoft SQL Server Trace Flags

    Complete list of Microsoft SQL Server trace flags (585 trace flags) REMEMBER: Be extremely careful w ...

  9. sql server 小技巧(7) 导出完整sql server 数据库成一个sql文件,包含表结构及数据

    1. 右健数据库 –> Tasks –> Generate Scripts   2. 选择所有的表   3. 下一步,选择Advanded, Types of data to script ...

随机推荐

  1. Centos常用快捷键

    终端快捷键  tab=补全 ctrl+a=开始位置 ctrl+e=最后位置 ctrl+k=删除此处至末尾所有内容 ctrl+u=删除此处至开始所有内容 ctrl+d=删除当前字母 ctrl+w=删除此 ...

  2. post请求返回 读取 HTML 表单 URL 编码的数据流时出错

    <httpRuntime maxRequestLength="1048576" executionTimeout="3600" /> 网站配置 限制 ...

  3. 完全卸载vs2013 2015

    /uninstall /force 解压你的vs2013的安装包(iso格式). cd到解压后的文件夹 vs_ultimate.exe /uninstall /force 或者创建一个快捷方式到桌面 ...

  4. MySQL存储过程错误No data - zero rows fetched, selected, or processed

    原因:游标没有获取到任何内容! 解决方案 : 声明一个 continue handler declare continue handler for not found set V_NotFound = ...

  5. Problem B 字符串类(I)

    封装一个字符串类,用于存储字符串和处理的相关功能,支持以下操作: 1. STR::STR()构造方法:创建一个空的字符串对象. 2. STR::STR(const char *)构造方法:创建一个字符 ...

  6. js 唤起APP

    常常有这样的场景,咱们开发出来的APP需要进行推广,比如在页面顶部来一张大Banner图片,亦或一张二维码.但往往我们都是直接给推广图片加了一个下载链接(App Store中的).所以咱们来模拟一下用 ...

  7. CodeForces - 780C Andryusha and Colored Balloons(dfs染色)

    Andryusha goes through a park each day. The squares and paths between them look boring to Andryusha, ...

  8. MVC中如何避免POST请求中出现的重复提交

    使用惯了Asp.Net的服务器控件了, 突然转到MVC框架上来遇到这么个问题. 比如说网速慢的时候, 用户频繁的点击提交按钮, 或者是按F5刷新页面等等.解决方法很简单. 解决方案 1. 在页面生成时 ...

  9. 20165326 java第五周学习笔记

    第五周学习笔记 ch7 内部类(&外嵌类) 内部类的类体不可以声明类变量和方法 内部类如同类的变量或方法 内部类和外嵌类在编译时生成两个class文件 匿名类 某个类的一个子类没有明显的用类声 ...

  10. ESP8266 上线

    1.首先配置esp8266 WIFI模块 使用USB转 TTL 连接 esp8266 WIFI模块,波特率115200 //查询固件版本 AT+GMR //设置WiFi应用模式为Station AT+ ...