GraphQL schemas, queries and resolvers.

In the previous example we learned how to run GraphQL with Express http server and we created a simple query example with returns hardcoded data. Let’s make this useful and create real world example.

Adding Nodemon for rapid development.

Before we continue, let’s make development process easier and run the project using Nodemon instead of Node. Nodemon is the same like Node but it also monitors the project folder for changes, and automatically restarts the server for us.

yarn add nodemon --dev

Creating schema and resolvers.

Technically speaking we already created our schema and resolver in the previous example. Let’s quickly go through what we did:

The most basic way to create a response in GraphQL is like it was described in the previous tutorial: creating schema describing the field name and type i.e.

var schema = buildSchema(`
  type Query {
    hello: String
  }
`);

and then creating a resolver i.e.

var root = {
  hello: () => {
    return 'Hello world!';
  },
};

which simply returns whatever is in the return statement: in this case “hello world!” for any hello field request.

Let’s make the example more useful by

Passing parameters.

The basic types that we could use out of the box are StringIntFloatBoolean, and ID

Let’s change the hello query to accept userName parameter of type String and prints ‘hello [userName]’. Also we will add another field called rollDice and will return a random number between 0 and 10.
Passing parameters requires two steps:
– define the parameter in the schema (line 8) hello(userName:String!): String
– read the parameter in the resolver (line 15) hello: (args) => { ...

./server.js

var express = require('express');
var graphqlHTTP = require('express-graphql');
var { buildSchema } = require('graphql');

// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
  type Query {
    hello(userName:String!): String,
    rollDice: Int
  }
`);
// The root provides a resolver function for each API endpoint

var root = {
  hello: (args) => {
    return `Hello ${args.userName}`;
  },
  rollDice: () => {
    return Math.floor(Math.random() * 6) + 1;
  }
};

var app = express();
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));

app.listen(4000);
console.log('Running a GraphQL API server at localhost:4000/graphql');

 what we just did:
– we added userName parameter in the schema and defined it as s String type (line 8)
– in the resolver we are getting the userName parameter from the args parameter, and returning the greeting line 16.
– in addition we also added another field call rollDice which returns a random number between 0 and 10.

Making queries with parameters.

Save the file and navigate the browser to http://localhost:4000/graphql

GraphQL UI

 

Explore the schema using documentation explorer.

Look at the top right side in the browser (picture above) and you will find the Documentation explorer (If it is collapsed click on ‘Docs’ in the upper right section). Let’s pretend that we didn’t build the schema but we still need to know what queries we could fire. That’s where Documentation explorer could help.
Click on Query and you will see this:

hello(userNameString!): String
This describes the ‘hello’ and the ‘rollDice’ queries, the input parameters and the output type.

Making the query.

Since now we know the query name and the parameters and their types we are ready to write our first query with parameters.

Add the query in the up left text box like it’s shown on the picture above,

query queryLabel($userName: String!) {
  hello(userName: $userName)
}

and then add the parameter in the left, down box named query variables. When we write query with parameters it’s always better instead to directly pass the parameter value, to use the $ syntax to define a variable in the query.

{
  "userName": "Sam Smith"
}

 what we just did:
– we described a query with label queryLabel and input parameter called $userName of type String
– The ! symbol means that $userName can’t be null
– (line 2) we are querying hello and passing $userName as a parameter
– in the second code snipped (under query variables) we are passing the actual value of our parameters. In our case the value of $userName

Hit the play button in the upper left section and you will get the response:

{
  "data": {
    "hello": "Hello Sam Smith"
  }
}

If we also want to query the rollDice we could just add this to our query:

query queryLabel($userName: String!) {
  hello(userName: $userName)
  rollDice
}

The great thing about GraphQL is that it will return only the queries that we requested, and also we could combine multiple queries (from the same schema) in one response.

Leave a Reply