How to find out which mutation is being requested when configuring “Context”(Node.js, Apollo Server)

Viewed 402

I would like to add conditional function on context depending on which mutation is being called in Node.js, Apollo Server.

How would I do that efficiently?

When configuring context, I have access to the request body and all the graphql request information is stored at “req.body.query”, which also contains what I need. To make use of this, I would have to parse with the “parse” function from “graphql” module. But I dont think this is efficient, cuz now the same request is basically getting parsed twice(once by me and once by Apollo Server). Also the parsed result is not very user friendly with all the nested values.

Is there a clean way to know what mutation is being requested?

1 Answers

One common solution to this is the use of operation names. The client can provide an operation name to the server in the request to identify what it is doing.

{
  "query": "{ mutation AddToBasket($myVariable: AddToBasketInput!) { addToBasket(input: $myVariable) { id } } }",
  "operationName": "AddToBasket",
  "variables": { "myVariable": "someValue" }
}

I think you can access the operation name from the body like this:

const server = new ApolloServer({
  context: ({ req }) => {
    if (req.body.operationName === 'AddToBasket') {
      console.log("Found it!")
    }
  }
})

You can also create a plugin for Apollo Server that uses the didResolveOperation event to get the operation name value.

export class MyPlugin implements ApolloServerPlugin {
    async requestDidStart() {
        return {
            async didResolveOperation(
                requestContext
            ) {
                console.log(requestContext.operationName);
            },
        }
    }
}

Using operation name avoids a need to parse the GraphQL operation to determine which mutation is included in the request, but also requires the client to provide a known operation name value, which may or may not work for your use case.

Related