0

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! ....
}
Mortalus
  • 10,574
  • 11
  • 67
  • 117

1 Answers1

0

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)
  },
…
Michel Floyd
  • 18,793
  • 4
  • 24
  • 39
  • But this would eventually mean that I create a Rest like or RPC like api .. I really like the graph model .. I don't want to make a dedicated entry for fetching every entity from the root Query resolver .. – Mortalus Dec 30 '22 at 10:30