订阅的GraphQLObjectType

时间:2020-06-04 14:18:41

标签: graphql graphql-js express-graphql graphql-subscriptions graphql-schema

我使用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();
          }
        }
      })
    });

1 个答案:

答案 0 :(得分:-1)

我使用订阅的方式是创建一个订阅服务器,并在客户端进行订阅。看看这个你就明白了。 https://youtu.be/r5KY5m5OXsI