我使用 Express 实现了一个 GraphQL 服务器,但我在设置 GraphQL 订阅类型时遇到了问题。
我正在开发一个实时聊天应用程序,并试图在创建新消息后发布一个事件,但我不明白我应该如何为订阅创建一个 GraphQLObjectType。
我尝试使用“graphql-subscriptions”中的 PubSub 和 WithFilter,但我不知道该怎么做。
const pubsub = new PubSub();
const NEW_MESSAGE = 'NEW_MESSAGE';
const Subscription = new GraphQLObjectType({
name: 'Subscription',
fields: () => ({
newMessage: {
subscribe: withFilter(() => pubsub.asyncIterator(NEW_MESSAGE), (payload, args) => {
return payload.recipientId === args.recipientId;
}),
**type: ?**
}
})
});
这是我创建的 MessageType:
const MessageType = new GraphQLObjectType({
name: 'Message',
fields: () => ({
id: { type: GraphQLID },
message: { type: GraphQLString },
senderId: { type: GraphQLID },
recipientId: { type: GraphQLID }
})
});
和 sendMessage 突变:
const Mutation = new GraphQLObjectType({
name: 'Mutation',
fields: () => ({
sendMessage: {
type: MessageType,
args: {
message: { type: GraphQLString },
senderId: { type: GraphQLID },
recipientId: { type: GraphQLID }
},
resolve: (parent, args) => {
const { message, senderId, recipientId } = args;
const msg = new Message({ message, senderId, recipientId });
pubsub.publish(NEW_MESSAGE, {
recipientId,
newMessage: message
});
return msg.save();
}
}
})
});