Custom field not getting published in subscription


#1

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:

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


#2

For everybody who is facing this, here is the solution: https://stackoverflow.com/questions/45769302/custom-field-not-getting-published-in-subscription-apollo-server/45772146#45772146