graphql - 使用来自 apollo-link-ws 的 WebSocketLinks 时添加 Graph*I*QL 订阅端点?
问题描述
这是我初始化 ApolloClient 的客户端代码:
import React from "react";
import {Meteor} from "meteor/meteor";
import {render} from "react-dom";
import {ApolloProvider} from "react-apollo";
import {ApolloLink, from} from "apollo-link";
import {ApolloClient} from "apollo-client";
import {HttpLink} from "apollo-link-http";
import {InMemoryCache} from "apollo-cache-inmemory";
import {onError} from 'apollo-link-error';
import {split} from 'apollo-link';
import {WebSocketLink} from 'apollo-link-ws'; //<======
import {getMainDefinition} from 'apollo-utilities';
import {toIdValue} from 'apollo-utilities';
import App from "../../ui/App";
// Create an http link:
const httpLink = new HttpLink({
uri: Meteor.absoluteUrl("graphql"),
credentials: 'same-origin'
})
// Create a WebSocket link:
const wsLink = new WebSocketLink({
uri: `ws://localhost:3200/subscriptions`,
options: {
reconnect: true
}
});
// using the ability to split links, you can send data to each link
// depending on what kind of operation is being sent
const splitLink = split(
// split based on operation type
({query}) => {
const {kind, operation} = getMainDefinition(query);
return kind === 'OperationDefinition' && operation === 'subscription';
},
wsLink,
httpLink,
);
const authLink = new ApolloLink((operation, forward) => {
const token = Accounts._storedLoginToken();
operation.setContext(() => ({
headers: {
"meteor-login-token": token
}
}));
return forward(operation);
});
const client = new ApolloClient({
link: ApolloLink.from([
onError(({graphQLErrors, networkError}) => {
if (graphQLErrors)
graphQLErrors.map(({message, locations, path}) =>
console.log(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
),
);
if (networkError) console.log(`[Network error]: ${networkError}`);
}),
authLink,
splitLink,
]),
cache: new InMemoryCache({})
});
const ApolloApp = () => (
<ApolloProvider client={client}>
<App/>
</ApolloProvider>
);
Meteor.startup(() => {
render(<ApolloApp/>, document.getElementById("app"));
});
这在客户端上完美运行。并使用它图表I ql(请注意“I”)适用于查询和突变。但是图I ql 还不适用于订阅,因为我还没有告诉它订阅端点。
在使用 WebSocketLinks 而不是 Express 时,搜索 SO 的答案似乎没有出现任何适用的问题。
使用 WebSocketLinks 时,告诉图形I ql 订阅端点的正确方法是什么?
解决方案
推荐阅读
- google-cloud-platform - 将其他语言输出到 Cloud Pub/Sub 主题
- c# - 如何从 XAML/WPF 中的不同网站加载 reCaptcha?
- sql - 数据库理解
- excel - 除法结果为0
- curl - virtualbox ping,telnet 工作但不卷曲
- python - pandas 按分位数过滤会产生一个空集
- c# - 如何使用 c# 获取 Instagram 故事集锦?
- javascript - 从 html 脚本标签(内联)访问 webpack 捆绑的 javascript 文件中的变量
- laravel - 如何在laravel中获取实时数据
- git - 在上一次提交合并 master 之后将分支合并到 master 然后将其还原