GraphQL订阅益智游戏

时间:2018-12-17 04:21:53

标签: websocket graphql apollo

在客户端上使用apollo-link,在服务器上使用apollo-server-express的PubSub。在与GraphQL API进行的摩卡测试中得到奇怪的结果:

摩卡咖啡:

import { execute, makePromise } from 'apollo-link';

const uri = 'http://localhost:3001/graphql';
const link = new HttpLink({ uri, fetch });

const subscribe = (query, handlers) => {
  const operation = {
    query: gql`${query}`,
  };

  return execute(link, operation).subscribe(handlers);
};


  const handlers = {
    next: (data) => {
      console.log(`received data: ${Date.now()}, ${JSON.stringify(data, null, 2)}`);
    },
    error: error => console.log(`received error ${error}`),
    complete: () => console.log('complete'),
  };

  it('subscribe', async () => {
    const query = `subscription {
      info
    }`;
    subscribe(query, handlers);
  });

服务器:

try {
  console.log('subscription =>| ', Date.now(), '|', line);
  worker.pubsub.publish('infoTopic', { info: line });
} catch (e) {
  console.error(e);
}

这是我从测试中看到的内容:

  

收到的数据:1545013826838,{“错误”:[       {         “ message”:“无法为不可为空的字段Subscription.info返回null。”,...

(来自服务器):

  

订阅=> | 1545013826887 |信息深度1选择深度1 ...

订户收到826 838 , 但发布商的发送时间是826 887

到底是什么?

1 个答案:

答案 0 :(得分:1)

我刚遇到这个错误。我找到了一个解决方案,因为我需要发布的对象的字段名称与预订的字段名称匹配。为了说明这一点,请注意架构中的字段名称newPost与解析程序中的名称匹配,以及正发布到通道和订阅操作的对象的字段名称:

// schema
type Subscription {
    newPost: Post!
}

// subscription resolver
newPost: {
  subscribe(parent, args, { pubsub }, info)
    return pubsub.asyncIterator('new post')
  }
}

// in the event publisher
pubsub.publish('new post', { newPost: post })

// the subscription operation
subscription {
  newPost {
    id
    title
    body
    published
  }
}