21
votes

I'm learning about GraphQL and I'm very interested in the operation name the part of the query that comes after the query or mutation (depending on the root query type). I found a couple of code examples using the operation name, and I'm confused as to where they come from? There seems to be no references in the code about them, and they seem completely arbitrary.

query Welcome {
  echo (email: "[email protected]")
}

and

query HeroNameQuery {
  hero {
    name
  }
}

I don't understand why a given schema can't just contain the queries and types that follow (eg. user, article, order, etc.), and I don't understand the namespacing system and the operation name provides any sort of advantage.

https://github.com/mugli/learning-graphql/blame/master/7.%20Deep%20Dive%20into%20GraphQL%20Type%20System.md#L436

http://graphql.org/docs/queries/

3
I'm pretty sure the name can be omitted (I think query too) if you're only sending one. I believe the names are basically used for stored queries. You could put those on the server and execute them by name rather than sending the whole query...I believe that's the idea, but I'm a GQL noob too. - mpen

3 Answers

14
votes

In GraphiQL you can choose from a list of queries specified by the operation name. Here's some screenshots to help make this make sense.

enter image description here

When you have two mutations / queries side-by-side and they don't have an operation name you can't run them.

When they have operation names they can be listed when you click the play / run button.

enter image description here

This is the biggest case for having an operation name that I've seen so far.

But it's not necessary because when you just have run query / mutation that's what's gonna run.

enter image description here

10
votes

The Query/Mutation name is optional. You can use it on the backend for stored queries if your backend supports it. However, it is generally used for logging. You can use a unique name for each query/mutation. Then, when you are having problems, you can grep through your logs for the query name to see what was happening with that specific query.

7
votes

That's a great question. The operation name is pretty much up to you on what you want to call it. However, you do need it when you pass in query / mutation parameters like so:

// GraphQL Query

query Welcome ($data: String!) {
  echo (email: $data) {
    name
  }
}

// GraphQL Variables

{
  "data": "[email protected]"
}

As for the return fields, you must write out the subfields of a given typed selection since GraphQL's philosophy is that everything is strongly-typed and the client dictates exactly what data it needs down to the subfield.

Hope this helps!