Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to approach a GraphQL query that returns a boolean value?

Need to check whether an email is available or taken during the user sign-up process. The goal is to quickly query, using GraphQL, the API server and have it tell us if the email is available or taken.

What is the general best practice on a simple boolean-ish type of situation using GraphQL?

Below is what I have come up with but I am unsure if this is a good practice or not and want to hear feedback on a better practice on queries like this.

Request:

query {
  emailExists(email:"[email protected]") {
    is
  }
}

Response:

{
  "data": {
    "emailExists": {
      "is": true
    }
  }
}
like image 849
Chad Taylor Avatar asked Jul 04 '19 00:07

Chad Taylor


People also ask

How do I get data from a GraphQL query?

You can fetch data very simply with the help of the package graphql-request . GraphQL Request is a library that doesn't require you to set up a client or a Provider component. It is essentially a function that just accepts an endpoint and a query.

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. In order to describe what happens when a query is executed, let's use an example to walk through.

Can GraphQL return an object?

In other words, if you return an empty object ( {} ), an empty array ( [] ) or some other value, GraphQL will treat this as you returning an object and not a null value!


1 Answers

A "query" is just a field on what happens to be the Query type. A field can return any output type, including scalars -- it doesn't need to return an object. So it's sufficient to have a schema like:

type Query {
  emailExists(email: String!): Boolean!
}

The only reason to prefer an object type would be if you anticipated wanting to add additional fields in the future (i.e. something other than your current is field).

like image 74
Daniel Rearden Avatar answered Sep 18 '22 12:09

Daniel Rearden