简体   繁体   English

Apollo graphQL 服务器订阅初始响应

[英]Apollo graphQL Server subscription initial response

I've successfully got graphQL subscriptions to work with help of the documentation.在文档的帮助下,我已成功获得 graphQL 订阅。

The subscription returns a pubsub.asyncIterator("MY_TOPIC"), which I then can send messages trough.订阅返回一个 pubsub.asyncIterator("MY_TOPIC"),然后我可以通过它发送消息。 Now I would like to send the current value to the new subscriber, and only the new subscriber, on subscription.现在我想在订阅时将当前值发送给新订阅者,并且只发送给新订阅者。

As the pubsub.asyncIterator("MY_TOPIC")() is a shared async iterator I guess I need a wrapper, which itsef is an async iterator, which returns the current value and thereafter "becomes" the shared pubsub.asyncIterator("MY_TOPIC")().由于 pubsub.asyncIterator("MY_TOPIC")() 是一个共享的异步迭代器,我想我需要一个包装器,它 itsef 是一个异步迭代器,它返回当前值,然后“成为”共享的 pubsub.asyncIterator("MY_TOPIC" )()。

Any ideas on how to accomplish that?关于如何实现这一目标的任何想法?

const mySubscription = {
  subscribe: async (parent, args, context, info) => {
    return context.pubsub.asyncIterator("MY_TOPIC")
  },
  resolve: payload => {
    return payload
  },
}

EDIT: It seems like sometime a good night of sleep is worth a lot.编辑:似乎有时候睡个好觉很值得。

const mySubscription = {
  subscribe: async (parent, args, context, info) => {
    return (async function* () {
      yield 123; //let this be my current state
      for await (const val of context.pubsub.asyncIterator("MY_TOPIC")) {
        yield val;
      }
    })()
  },
  resolve: payload => {
    return payload
  },
}

As far as I can see I just create a wrapper generator, which returns my desired value and afterwards iterates over the pubsub async iterator.据我所知,我只是创建了一个包装器生成器,它返回我想要的值,然后迭代 pubsub 异步迭代器。 I tried that before, but forgot about the await in the for await of loop.我之前尝试过,但是忘记了 for await of loop 中的 await 。 And obviously the pubsub AsyncIterator is not syncronously iterable.显然,pubsub AsyncIterator 不是可同步迭代的。 Are there any sideffects I'm missing?我缺少任何副作用吗?

It sounds like you need a filter for your subscription, have a look at the example here ...听起来你的订阅需要一个过滤器,看看这里的例子......

It may look like this:它可能看起来像这样:

import { withFilter } from 'graphql-subscriptions';

const currentUsers = [];
const resolvers = {
  Subscription: {
    myTopic: {
      subscribe: withFilter(
        () => pubsub.asyncIterator('MY_TOPIC'),
        (payload, variables) => {
          // Only push an update if it is a new subscriber
          if (!currentUsers.includes(variables.username)) {
            currentUsers.push(variables.username);
            return true;
          }
          return false;
        },
      ),
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM