订阅
当我们最初设置Apollo的时候,我们使用Apollo Boost来安装所需的依赖项。 但是订阅是一个高级用例,Apollo Boost并不支持。因此,我们必须安装更多的依赖项来设置订阅。
React Apollo 订阅设置
+ $ npm install subscriptions-transport-ws --save
现在我们需要更新我们的ApolloClient
实例以指向订阅服务器。
打开src/components/App.js
并更新以下导入:
- import { ApolloClient, ApolloProvider, InMemoryCache, HttpLink } from '@apollo/client';+ import { ApolloClient, ApolloProvider, InMemoryCache } from '@apollo/client';+ import { WebSocketLink } from "@apollo/client/link/ws";
更新创建Apollo客户端的功能以集成WebSocket链接。
const createApolloClient = (authToken) => {return new ApolloClient({- link: new HttpLink({+ link: new WebSocketLink({- uri: 'https://hasura.io/learn/graphql',+ uri: 'wss://hasura.io/learn/graphql',+ options: {+ reconnect: true,+ connectionParams: {headers: {Authorization: `Bearer ${authToken}`}+ }+ }}),cache: new InMemoryCache(),});};
请注意,我们正在用WebSocket链接取代Http链接,因此所有GraphQL查询都要通过一个单一的Websocket连接。
Did you find this page helpful?
Start with GraphQL on Hasura for Free
- Build apps and APIs 10x faster
- Built-in authorization and caching
- 8x more performant than hand-rolled APIs