我正在使用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();
服务器:
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); } }, }; ...