Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine a mutation and a query in a single query?

I have an operation getFoo that requires that the user is authenticated in order to access the resource.

User authenticates using a mutation authenticate, e.g.

mutation {
  authenticate (email: "foo", password: "bar") {
    id
  }
}

When user is authenticated, two things happen:

  1. The request context is enriched with the authentication details
  2. A cookie is created

However, I would like to combine authentication and getFoo method invocation into a single request, e.g.

mutation {
  authenticate (email: "foo", password: "bar") {
    id
  }
}
query  {
  getFoo {
    id
  }
}

The latter produces a syntax error.

Is there a way to combine a mutation with a query?

like image 354
Gajus Avatar asked Oct 12 '17 20:10

Gajus


People also ask

How do you pass two arguments in GraphQL query?

Multiple arguments can be used together in the same query. For example, you can use the where argument to filter the results and then use the order_by argument to sort them.

What is the difference between query and mutation?

A mutation can contain multiple fields, just like a query. There's one important distinction between queries and mutations, other than the name: While query fields are executed in parallel, mutation fields run in series, one after the other.

How do you create a nested query in GraphQL?

You can use the object (one-to-one) or array (one-to-many) relationships defined in your schema to make a nested query i.e. fetch data for a type along with data from a nested or related type. The name of the nested object is the same as the name of the object/array relationship configured in the console.

Can GraphQL schema have multiple queries?

When doing query batching, the GraphQL server executes multiple queries in a single request. But those queries are still independent from each other. They just happen to be executed one after the other, to avoid the latency from multiple requests.


1 Answers

There's no way to send a mutation and a query in one request according to the GraphQL specification.

However, you can add any fields to the mutation payload. So if there are only a handful of queries that you need to support for the authenticate mutation, you could to this, for example:

mutation {
  authenticate (email: "foo", password: "bar") {
    id
    getFoo {
      id
    }
  }
}

At the end of the day, it might be better to keep the mutation and query separate though. It gets hairy very quickly if you want to include many queries in many mutations like this. I don't see a problem with the overhead of an additional request here.

like image 170
marktani Avatar answered Oct 26 '22 15:10

marktani