Sign up for Hasura Newsletter
Loading...

订阅

当我们最初设置Apollo的时候,我们使用Apollo Boost来安装所需的依赖项。 但是订阅是一个高级用例,Apollo Boost并不支持。因此,我们必须安装更多的依赖项来设置订阅。

React Apollo 订阅设置

+ $ npm install subscriptions-transport-ws --save

现在我们需要更新我们的ApolloClient实例以指向订阅服务器。

打开src/components/App.js并更新以下导入:

githubsrc/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
  • ArrowBuild apps and APIs 10x faster
  • ArrowBuilt-in authorization and caching
  • Arrow8x more performant than hand-rolled APIs
Promo
footer illustration
Brand logo
© 2024 Hasura Inc. All rights reserved
Github
Titter
Discord
Facebook
Instagram
Youtube
Linkedin