Apollo 订阅:Apollo Graphql 正在 Playground 上接收更新,但不在客户端上

Ily*_*rim 5 apollo reactjs graphql graphql-subscriptions apollo-client

我正在对 Apollo GraphQL 订阅使用 react,我可以在 Apollo Playground 上接收更新,但不能在客户端上接收更新。这是阿波罗游乐场的回应:

在此处输入图片说明

Graphql 服务器已开启http://localhost:4000/并在 ws://localhost:4000/graphql 上订阅。但是,它适用于操场,但不适用于客户端。我以这种方式设置 Apollo 客户端以接收来自服务器的更新:

import ApolloClient from 'apollo-boost';
import { WebSocketLink } from 'apollo-link-ws';
import { HttpLink } from 'apollo-link-http';
import { split } from 'apollo-link';
import { getMainDefinition } from 'apollo-utilities';

const httpLink = new HttpLink({
  uri: 'http://localhost:4000/graphql'
});

export const wsLink = new WebSocketLink({
  uri: `ws://localhost:4000/graphql`,
  options: {
    reconnect: false
  }
});

export const link = split(
  // split based on operation type
  ({ query }) => {
    const definition = getMainDefinition(query);
    return (
      definition.kind === 'OperationDefinition' &&
      definition.operation === 'subscription'
    );
  },
  wsLink,
  httpLink,
);



export const client = new ApolloClient({
  uri: 'http://localhost:4000/',
});
Run Code Online (Sandbox Code Playgroud)

在我看来,我已经使用了useSubscriptions

const MESSAGE_SENT_SUBSCRIPTION =  gql`subscription {
  messageSent {
    id
    message
  }
}`
const {data: newMessage, loading: newMessageLoading} = useSubscription(MESSAGE_SENT_SUBSCRIPTION, {});
Run Code Online (Sandbox Code Playgroud)

在渲染时,我使用了:

{!newMessageLoading && JSON.stringify(newMessage)}
Run Code Online (Sandbox Code Playgroud)

但是从客户端,它没有收到更新,但我确信它与 Graphql WebSockets 服务器连接。

oc

服务器端:

let database = require("./src/database.js")
let schema = require("./src/schema.js");
let resolvers = require("./src/resolvers.js");
let {ApolloServer} = require("apollo-server");

// The ApolloServer constructor requires two parameters: your schema
// definition and your set of resolvers.
const server = new ApolloServer({ 
  typeDefs: schema, 
  resolvers: resolvers,
  context: {
    database
  }
});

// The `listen` method launches a web server.
server.listen().then(({ url,subscriptionsUrl ,subscriptionsPath}) => {
  console.log(`  Server ready at ${url}`);
  console.log(`realtime here at ${subscriptionsUrl} and path ${subscriptionsPath}`)
});
Run Code Online (Sandbox Code Playgroud)

我在这里做错了什么,有没有人遇到过这样的问题?

Art*_*kiy 2

您需要将分割链接传递给 ApolloClient 构造函数。尝试像这样传递它(客户端):

import ApolloClient from 'apollo-boost';
import { WebSocketLink } from 'apollo-link-ws';
import { HttpLink } from 'apollo-link-http';
import { split } from 'apollo-link';
import { onError } from 'apollo-link-error';
import { getMainDefinition } from 'apollo-utilities';

const httpLink = new HttpLink({
  uri: 'http://localhost:4000/graphql'
});

export const wsLink = new WebSocketLink({
  uri: `ws://localhost:4000/subscriptions`,
  options: {
    reconnect: false
  }
});

export const link = split(
  // split based on operation type
  ({ query }) => {
    const definition = getMainDefinition(query);
    return (
      definition.kind === 'OperationDefinition' &&
      definition.operation === 'subscription'
    );
  },
  wsLink,
  httpLink,
);

export const graphqlServer = 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}`);
            }
        }),
        link // YOUR LINK (NOW MATCHING YOUR CODE)
    ])
});
Run Code Online (Sandbox Code Playgroud)

和服务器端:

...
const server = new ApolloServer({ 
  typeDefs: schema, 
  resolvers: resolvers,
  subscriptions: {
        path: '/subscriptions'
  },
  context: {
    database
  }
});
...
Run Code Online (Sandbox Code Playgroud)

请注意,/subscriptions也传递给 ApolloClient