avoid calling a parent resolver if only nested resolver was called

25 views Asked by At

lets say I have a simple query to get post's comments and it looks like this

post(id:"123") {
  comments: {
    id,
    body
  }
}

currently it the graph will call postResolver and then commentsResolver but the call to postResolver is redundant since I only need to fetch all the comments by postId

I am using an implementation using nodeJs with typescript

i have a resolver such as this

const resolvers : Resolvers = {
  Query: {
     post: (parent, args, info) => { return fetchPost(args.id);}
  },

  Post: {
     comments: (parent, args, info) => { return fetchComments(parent.id)}
  }
}

basically in this example I don't need to fetch the post at all, but the resolver is still invoked, any way to elegantly avoid it ?

I'm looking of a generalized pattern and not this specific resolver situation, there are other nodes with same situation would like to know if there is anything common in this situation that was already solved ...

My solution so far is to remodel the graph like this

type Post (id: ID!){
  postData: PostData,
  comments: [Comment!]
}

type PostData {
  id: ID! ...
}

type Comment{
  id: ID! ....
}
1

There are 1 answers

1
Michel Floyd On

Your original model is fine, you just need a different query that goes straight for the comments based on their postId:

getCommentsByPostId(postId: ID!): [Comment]

Then augment your query resolvers:

const resolvers : Resolvers = {
  Query: {
     post: (_, { id }) => { return fetchPost(id);},
     getCommentsByPostId: (_, { postId }) => fetchComments(postId)
  },
…