【问题标题】:Pubsub publish multiple events Apollo ServerPubsub 发布多个事件 Apollo Server
【发布时间】:2020-05-30 14:04:10
【问题描述】:

我正在使用 Apollo Server,我想从同一个解析器连续发布 2 个事件。两种订阅都可以正常工作但前提是我只发送一个事件。如果我尝试同时分派两者,则永远不会调用第二个订阅解析器。如果我注释掉第一个事件调度第二个正常工作。

const publishMessageNotification = async (message, me, action) => {
  const notification = await models.Notification.create({
    ownerId: message.userId,
    messageId: message.id,
    userId: me.id,
    action,
  });

 // if I comment out this one, second pubsub.publish starts firing
  pubsub.publish(EVENTS.NOTIFICATION.CREATED, {
    notificationCreated: { notification },
  });

  const unseenNotificationsCount = await models.Notification.find({
    ownerId: notification.ownerId,
    isSeen: false,
  }).countDocuments();

  console.log('unseenNotificationsCount', unseenNotificationsCount);// logs correct value

  // this one is not working if first one is present
  pubsub.publish(EVENTS.NOTIFICATION.NOT_SEEN_UPDATED, {
    notSeenUpdated: unseenNotificationsCount,
  });
};

我正在使用默认的 pubsub 实现。控制台中没有错误。

import { PubSub } from 'apollo-server';

import * as MESSAGE_EVENTS from './message';
import * as NOTIFICATION_EVENTS from './notification';

export const EVENTS = {
  MESSAGE: MESSAGE_EVENTS,
  NOTIFICATION: NOTIFICATION_EVENTS,
};

export default new PubSub();

【问题讨论】:

  • 控制台中是否显示任何错误?您使用的是哪种 PubSub 实现?
  • 我在编辑后的问题中回答了。
  • 我的订阅仅在页面刷新后才开始工作。它必须通过 websocket 进行身份验证。

标签: graphql publish-subscribe subscription apollo-server


【解决方案1】:

确保您使用来自 apollo 服务器上下文的 pubsub,例如:

服务器:

const server = new ApolloServer({
  schema: schemaWithMiddleware,
  subscriptions: {
    path: PATH,
    ...subscriptionOptions,
  },
  context: http => ({
    http,
    pubsub,
    redisCache,
  }),
  engine: {
    apiKey: ENGINE_API_KEY,
    schemaTag: process.env.NODE_ENV,
  },
  playground: process.env.NODE_ENV === 'DEV',
  tracing: process.env.NODE_ENV === 'DEV',
  debug: process.env.NODE_ENV === 'DEV',
});

以及在解析器中的使用示例,按上下文:

...
const Mutation = {
  async createOrder(parent, { input }, context) {
    ...
    try {
       ...
        context.pubsub.publish(CHANNEL_NAME, {
          newMessage: {
            messageCount: 0,
          },
          participants,
        });
        dialog.lastMessage = `{ "orderID": ${parentID}, "text": "created" }`;
        context.pubsub.publish(NOTIFICATION_CHANNEL_NAME, {
          notification: { messageCount: 0, dialogID: dialog.id },
          participants,
        });
        ...
      }
      return result;
    } catch (err) {
      log.error(err);
      return sendError(err);
    }
  },
};
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-30
    • 2019-06-04
    • 2022-12-10
    • 2020-11-03
    • 1970-01-01
    • 2018-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多