1

I have a graphql type UserReview and UserReply:

type UserReview {
  _id
  content
}

type UserReply {
  _id
  reviewId
  content
}

I'm using graphql-compose to do add a relation between reviews and replies so that when querying a review I will also get a list associated replies with the review - this works. Now I want to perform some data manipulation on the result. First I tried adding resolver middleware in graphql-compose. But the result of userReviews resolver is just an array of reviews without replies. After adding some console.log statements I noticed that the relation which populates the replies field of review is run after reviews resolver is run which makes sense because child resolver needs parent data first.

But I still need to somehow intercept the result before it's returned to the client. So I thought maybe I need to intercept it not at graphql-compose level but on graphql server lever (I'm using Apollo server). So I added another kind of middleware:

import { applyMiddleware } from 'graphql-middleware'
import { schemaComposer } from 'graphql-compose'
export { UserReviewTC, UserReplyTC } from './UserReview'

const userReviewsMiddleware = {
  Query: {
    userReviews: async (resolve, parent, args, context, info) => {
      const result = await resolve(parent, args, context, info);
      // the result here still doesn't include replies!
      return result;
    }
  }
};
export const schema = applyMiddleware(
  schemaComposer.buildSchema(),
  userReviewsMiddleware
);

but still the result from userReviewsMiddleware doesn't include replies field. My question is how to actually get the complete result with replies before it's returned to the client?

EDIT: I see that there's formatResponse in Apollo docs but it feels not right to perform data manipulation in formatResponse because I'd need to import modules which query the database inside formatQuery.

hitchhiker
  • 1,099
  • 5
  • 19
  • 44
  • What exactly kind of manipulations do you need ? ... probably can be done with normal resolvers. – xadm Mar 31 '20 at 16:25
  • I'm using built-in graphql-compose resolvers to do the heavy lifting so I don't want to write my own resolver unless there're no other options. – hitchhiker Mar 31 '20 at 16:57

0 Answers0