How can I use JSON API includes in a GraphQL resolver?

How can I use JSON API includes in a GraphQL resolver?

I’m curious how best to structure my GraphQL resolver for apollo-server to make use of an API’s ability to optionally resolve foreign keys (similar to JSON API’s includes). For example, you can request comments be included with a post by adding a parameter:
GET /articles/1?include=comments HTTP/1.1

However, the request for the record(s) is made at the level of the articles resolver. Can it somehow access the fields below it? Can the comments resolver somehow affect its parent?
I see there is a blog post on graphql.org that references a pull request designed to address this …that has since been abandoned by its author. What other approaches might I take? Is this fundamentally a limit of the current spec? Are there other changes on the horizon that might help?

Solutions/Answers:

Solution 1:

That’s an interesting use case 🙂

Your query is resolved in a top-down fashion, so the resolver for articles is called before the resolver for comments — there’s no way anything you do inside the comments resolver can affect what the articles resolver does.

However, each resolver is passed four arguments — (1) the object resolved by its parent field, (2) the arguments on its field, (3) the context and (4) a GraphQLResolveInfo object. This last one contains information about the query that was submitted to your server.

For example, let’s say you had a query like this:

query ArticlesQuery {
  articles {
    comments {
      text
    }
  }
}

The info object would look something like this:

{
  "fieldNodes": [
    "name": {
      "value": "articles"
    },
    selectionSet: [
      "name": {
        "value": "comments"
      },
      selectionSet: [
        "name": {
          "value": "text"
        }
      ]
    ]
  [
}

I’ve omitted a number of other fields, but you can see how the object is nested just like your query document. This makes it possible to iterate through it to check which fields were actually requested. You can then modify your API call appropriately.

Related:  Basic graphQL Mongoose set up

There’s also tools out there, like this one, that can help you parse the object more easily.

References