【问题标题】:GraphQL subscribe puzzlerGraphQL 订阅难题
【发布时间】:2019-05-17 10:45:30
【问题描述】:

在客户端使用 apollo-link,在服务器上使用来自 apollo-server-express 的 PubSub。在与 GraphQL API 对话的 mocha 测试中得到奇怪的结果:

摩卡:

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 seldepth 1 ...

订阅者在 826838 接收, 但发布者在 826887

发送

什么鬼?

【问题讨论】:

    标签: websocket graphql apollo


    【解决方案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
      }
    }
    

    【讨论】:

    • 谢谢,杰克。我终于让它工作了,尽管可能完全按照你上面所做的那样做。我发布了一篇关于它的hackernoon 文章here
    猜你喜欢
    • 2017-09-19
    • 2019-12-02
    • 2021-10-09
    • 2021-03-17
    • 2019-07-09
    • 2021-05-25
    • 2020-10-08
    • 2020-11-17
    • 2020-08-10
    相关资源
    最近更新 更多