apollographql / graphql-subscriptions

:newspaper: A small module that implements GraphQL subscriptions for Node.js
MIT License
1.59k stars 133 forks source link

Custom field not getting published in subscription #98

Closed lednhatkhanh closed 7 years ago

lednhatkhanh commented 7 years ago

My schema:

type Post {
    id: ID!
    title: String!
    content: String
    voteCount: Int!
    author: User!
    votes: [Vote!]!
    createdAt: Date!
    updatedAt: Date!
  }
type Subscription {
    Post(filter: PostSubscriptionFilter): PostSubscriptionPayload
  }
  input PostSubscriptionFilter {
    mutation_in: [_ModelMutationType!]
  }
  type PostSubscriptionPayload {
    mutation: _ModelMutationType!
    node: Post
  }
  enum _ModelMutationType {
    CREATED
    UPDATED
    DELETED
  }

Resolver

Mutation: {
    addPost: async (
      root,
      { title, content },
      { ValidationError, models: { Post }, user },
    ) => {
      if (!user) {
        throw new ValidationError('unauthorized');
      }
      const post = new Post({
        title,
        content,
        author: user.id,
      });
      await post.save();
      pubsub.publish('Post', { Post: { mutation: 'CREATED', node: post } });
      return post;
    },
},
Subscription: {
    Post: {
      subscribe: () => pubsub.asyncIterator('Post'),
    },
  },
Post: {
    // eslint-disable-next-line no-underscore-dangle
    id: root => root.id || root._id,
    author: async ({ author }, data, { dataLoaders: { userLoader } }) => {
      const postAuthor = await userLoader.load(author);
      return postAuthor;
    },
    voteCount: async ({ _id }, data, { models: { Vote } }) => {
      const voteCount = await Vote.find({ post: _id }).count();
      return voteCount || 0;
    },
    votes: async ({ _id }, data, { models: { Vote } }) => {
      const postVotes = await Vote.find({ post: _id });
      return postVotes || [];
    },
  },

And the subscription in React client:

componentWillMount() {
    this.subscribeToNewPosts();
  }
subscribeToNewPosts() {
    this.props.allPostsQuery.subscribeToMore({
      document: gql`
        subscription {
          Post(filter: { mutation_in: [CREATED] }) {
            node {
              id
              title
              content
              updatedAt
              voteCount
            }
          }
        }
      `,
      updateQuery: (previous, { subscriptionData }) => {
        // const result = Object.assign({}, previous, {
        //   allPosts: [subscriptionData.data.Post.node, ...previous.allPosts],
        // });
        // return result;
        console.log(subscriptionData);
        return previous;
      },
    });
  }

The field voteCount is undefined: image

While using queries or mutations, it get published normally, what should I do? Thank you.

lednhatkhanh commented 7 years ago

Found the solution here: https://stackoverflow.com/questions/45769302/custom-field-not-getting-published-in-subscription-apollo-server/45772146#45772146