Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a graphql query or mutation return a scalar value

Tags:

graphql

Syntactically you can define a query or a mutation in the schema such that it returns a type. However, an operation definition (i.e a query or mutation invoked by a client) has to have a SelectionSet, so I have to do:

mutation X { field }

So the result of my mutation or query has to be an object with fields, it can't be a scalar. Is this right? It feels like I ought to be able to just return a scalar. The result is always wrapped in an envelope when sending across HTTP, so the result would be valid JSON either way (a simple scalar isn't strictly valid JSON).

Is my reading correct?

like image 214
Tom Quarendon Avatar asked Oct 26 '18 07:10

Tom Quarendon


People also ask

What do GraphQL mutations return?

Dgraph automatically generates GraphQL mutations for each type that you define in your schema. The mutation field returns an object type that allows you to query for nested fields. This can be useful for fetching an object's new state after an add/update, or to get the old state of an object before a delete.

What does a GraphQL query return?

After being validated, a GraphQL query is executed by a GraphQL server which returns a result that mirrors the shape of the requested query, typically as JSON.

Can GraphQL return an object?

In many cases, you don't want to return a number or a string from an API. You want to return an object that has its own complex behavior. GraphQL is a perfect fit for this.

Can GraphQL mutation return nothing?

According to this Github issue you cannot return nothing. You can define a return type which is nullable e.g. But I suggest you return the id of the deleted element, because if you want to work with a cached store you have to update the store when the delete mutation has ran successfully.


1 Answers

You can actually return a scalar, like Boolean or String

type Mutation {
  hello(who: String!): String
}

The issuing this query

mutation foo {
  hello("peter")
}

result would look like this

data.hello // string

Tested this with graphql-yoga + graphql-playground:

schema from playground result from playground

like image 127
lipp Avatar answered Sep 20 '22 11:09

lipp