4

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();
          }
        }
      })
    });
Guy Ben David
  • 478
  • 3
  • 15

1 Answers1

-2

The way I use subscription is by creating a subscription server and subscribing to it on client side. Have a look at this you with understand. https://youtu.be/r5KY5m5OXsI

  • Please reserve the answer field for a complete informative solution. If you have a reference link, post the relevant information from that link directly in your answer. Be aware that links may become obsolete. – Ronald Jul 24 '20 at 17:41
  • @Ronald I am aware of it but its a link to YouTube video so I posted it. – Abhijeet Singh Jul 25 '20 at 18:06