GraphQL Resolver & Schema

Resolver – In GraphQL resolver is set of functions that generates the response for GraphQL queries. A resolver has four parameters.

Hi there, Let’s build graphql resolver and schema.

Prerequisites: please visit our first article on basics from here. It makes it easier to understand this article.

Resolver – In GraphQL resolver is a set of functions that generate the response for GraphQL queries. A resolver has four parameters.

A resolver is a function that’s responsible for populating the data for a single field in your schema. It can populate that data in any way you define, such as by fetching data from a back-end database or a third-party API

apollographql

Resolver function signature – as mentioned above resolver function has four parameters as given below.

ParameterDescription
Parent or rootThis contains the result of the resolver for this particular field’s
ArgsThis contains all the graphQL arguments.
Context or data source This is included data where the resolver functions are going to perform. on other word, this is an object shared by all resolvers in a specific query.
InfoThis is used in very advanced case. It contains information about the execution.
resolver parameters

Schema – Schema is core function of graphQL which client app can query on schema capabilities. Normally it describes the functionalities that are available in client application. In this blog we will do schema and resolver examples. Then you will have a clear picture on these. For this application we will be using apollo server npm package. It is an open source GraphQL server. You can find it here.

Let’s move to the steps to develop our app. If you followed our last GraphQL app, in this blog we will be developing same app using correct way in GraphQL.

Step 01: create project structure

Create the given project structure.

Step 02: Node Modules

You will get the node module folder one you install the given npm packages.

  • lodash
  • apollo-server

Step 03: add sample data into author.json

Add below given json data set into author.json you created.

[
    {
        "id": "1",
        "authorName": "William Shakespeare",
        "authorCountry": "United Kindom",
        "language": "English",
        "book": [
            {
                "id": 1,
                "name": "As You Like It",
                "isbn": 686523,
                "price": 56
            },
            {
                "id": 1,
                "name": "Lover's Complaint",
                "isbn": 563289314,
                "price": 15
            }
        ]
    },
    {
        "id": "2",
        "authorName": "Somerset Maugham",
        "authorCountry": "UK / US",
        "language": "English",
        "book": [
            {
                "id": 1,
                "name": "The magician",
                "isbn": 686523,
                "price": 50
            },
            {
                "id": 1,
                "name": "The painted veil",
                "isbn": 563289314,
                "price": 25
            }
        ]
    }
]

Step 04: code schema.js

In order to create graphQL schema, you have to import apollo server npm package.

const { ApolloServer, gql } = require('apollo-server');
const typeDefs = gql`
type Query{
    author(
    id:ID
    authorName:String
    authorCountry:String
    language:String):[Author],
    findAuthorById(id:ID):Author
}
type Author {
        id:ID!
        authorName:String!
        authorCountry:String
        language:String
        book:[Book]
    }
type Book {
        id:ID!
        name:String!
        price: Int
        isbn:Int!
        category:Category
    }
enum Category{
        NOVEL
        DRAMA
        POEMS
        BIOGRAPHY
        COMEDIES
    }
`
module.exports = typeDefs;

If you need to know in detail about schema properties, please visit out last article from here.

Step 05: code the authorService.js

Here you have to import data set and loadash npm package.

const author = require('../data/author.json');
const _ = require('lodash');
// Author service
class AuthorService {
    getAllAuthors(args) {
        // use _ for filter from any data
        return _.filter(author, args);
    }
    // filter data from id
    getAuthorById(id) {
        return author.filter(function (author) {
            return author.id == id;
        });
    }
}
module.exports = AuthorService

Step 06: code the resolver.js

Import the Authorservice.js.

const AuthorService = require('./dataSource/AuthorService');

Set up the data source.

// data source
const dataSources = () => ({
    authorService: new AuthorService()
})
// resolver
const resolvers = {
    Query: {
        // get author by id
        findAuthorById: (parent, { id }, { dataSources }, info) => {
// make sure to use getAuthorById function same as in AuthorService class
            return dataSources.authorService.getAuthorById(id)[0];
        },
        author: (parent, args, { dataSources }, info) => {
// make sure to use getAllAuthors function same as in AuthorService class
            return dataSources.authorService.getAllAuthors(args);
        }
    }
}
module.exports = { resolvers, dataSources };

findAuthorById and author are the resolver functions that are defined in the schema. As mentioned above you can see four parameters in the resolvers.  Using first resolver you will able to get author details passing author id but in the second resolver you can pass anything like id, name or any other author property and get the relevant output. If you code this in REST API, you need to have separate endpoints.

Step 07: code the server.js

Import the relevant npm package, resolver and schema.

const { ApolloServer, gql } = require('apollo-server');
const { resolvers, dataSources } = require('./resolver');
const typeDefs = require('./schema');
// create the server passing necessary params 
const gqlServer = new ApolloServer({ typeDefs, resolvers, dataSources });
gqlServer.listen({ port: process.env.port || 4000 })
    .then(({ url }) => { console.log(`GraphQL server started on ${url}`); })
    .catch(() => {
        console.log('Unable to start the server');
    });

All done 😍, now  you can run the application. Open the console and run the ‘node server.js’ or ‘nodemon server.js’ then you will get the apollo server graphQL UI tool (http://localhost:4000).

Now you can try queries. Write the below query and see the result.

query{
  findAuthorById(id:1){
  id
  authorName
    book{
      name
    }
  }
}

Result:

Filter by any property.

query{
  author(language:"English"){
  id
  authorName
    book{
      name
    }
  }
}

Result:

Try your last query with different parameters. It will work too. If you going to do this with REST, you need to have different end points.

You can download completed project from here. Don’t forget to hit npm install before run the project.

Reference

apollographql

Udara Chinthaka
Author: Udara Chinthaka

Total
0
Shares

Leave a Reply

Total
0
Share