CodeX
Published in

CodeX

Your GraphQL starter kit

Communication between the front-end and the back-end is a very important aspect of any web application. In this example, I will show you that implementing GraphQL for a new project and even adding it to an existing one is not as difficult as you may think.

With GraphQL, the data that you need for a particular part of your front-end can be fetched in one call, even in case the data is to be loaded from multiple sources.

In this very straightforward mini-tutorial, I will use javascript, but all major programming languages are supported as well.

What do we need to run a graphql query? Let’s find out with this very simple query with one single field:

{
ping
}

The response will be a single field as well:

{
"data": {
"ping": "pong"
}
}

The first thing we need to do is setting up a web server, here I will use express framework.

In order to allow the server to process graphql requests, we need to define types, resolvers, and of course, install some graphql libraries.

  1. Type definitions

Every field in your queries has to match a field in type definitions. The Query type object holds all the top-level fields, this is the “root” object, the first that we have to define.

const typeDefs = gql`type Query {  ping:String}`;

Graphql now knows that the query “ping” should return a string, the next step is defining the value of this string, using a resolver.

2. Resolvers

A resolver is a function that returns a value to be assigned to a particular field:

const resolvers = {  Query: {    ping: () => 'pong'  }};

A resolver function can take up to 4 parameters, but with our simple example, they are not needed, so we just use an arrow function.

3. Graphql server

We need to install the npm packages apollo-server-express together with graphql.

const express = require('express');const { ApolloServer, gql } = require('apollo-server-express');const gpserver = new ApolloServer({ typeDefs, resolvers });await gpserver.start();

const app = express();
gpserver.applyMiddleware({ app });

await new Promise(resolve => app.listen({ port: 4000 }, resolve));
console.log(`🚀 Server ready at http://localhost:4000${gpserver.graphqlPath}`);

Once the server has started, you can use the tool studio.apollographql.com to start sending queries.

Objects vs Scalars

Scalars are single-field data: String, Boolean, ID, Int and Float.

An object can be composed of multiple fields. Let’s say we want to create a shopping receipt from a grocery store. Here, ShoppingBag and ShopItem are two GraphQL object types with two fields each.

Let’s add a new field in the root query object: receipt, with the type ShoppingBag: we can now ask for the fields shop and items in our query.

Note that the field items expects an array of ShopItem objects.

const typeDefs = gql`
type ShoppingBag { shop: String items:[ShopItem] } type ShopItem { name: String price: Float } type Query { ping: String receipt: ShoppingBag }`;

Graphql always looks for additional resolvers when a field is an object type. Here we need a set of resolvers for the ShoppingBag object:

const resolvers = {
Query: { ping: () => 'pong', receipt: () => { return { shop:"Wallmart" }; } },
ShoppingBag: { shop(obj){ return obj.shop; }, items(obj){ return [ { name:"Water", price:20.5 }, { name:"Milk", price:30.5 } ] ; } }};

Here is our query for the “shopping receipt”:

{
receipt{
shop items{ name price } }}

And here is the response from graphql:

{   
"data": {
"receipt": {
"shop": "Wallmart",
"items": [
{ "name": "Water", "price": 20.5 },
{ "name": "Milk", "price": 30.5 }
]
}
}
}

If there were errors, they would be displayed under errors key, before data.

Databases

If your data is stored on a database, you can use context constructor to link your database client so that you can use it in your resolvers.

Remember: Do not use callbacks inside resolvers, use only promises.

const gpserver = new ApolloServer({ typeDefs, resolvers, context: async ()=>({ db: dbcli }) });

Front-end part

Once everything is ready on the server side, you can use the Apollo Client and get access to react hooks for your graphql queries. Combining the power of react with graphql will allow you to add new features easily.

Thank you for reading! You are now ready to run your first graphql query, and you can even start creating your own types and resolvers.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Amir Hachaichi

Amir Hachaichi

I write about web applications and javascript. I try to make tutorials that everyone can benefit from, regardless of the background