I implemented a GraphQL server using Express, and I have an issue with the setup of GraphQL Subscription type.
I'm developing a real time chat app and I'm trying to publish an event after a new message is created, but I don't understand how should I create a GraphQLObjectType for the subscription.
I tried to use PubSub and WithFilter from 'graphql-subscriptions' but I can't figure out how to do so.
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: ?**
}
})
});
Here is the MessageType I've created:
const MessageType = new GraphQLObjectType({
name: 'Message',
fields: () => ({
id: { type: GraphQLID },
message: { type: GraphQLString },
senderId: { type: GraphQLID },
recipientId: { type: GraphQLID }
})
});
And the sendMessage mutation:
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();
}
}
})
});