DEV Community

loading...

Build a graphql server with Apollo-express

MANOJ AP
Code well and try .. catch a coffee
・3 min read

Graphql is modern an alternative approach for the REST API invented by Facebook. It is used for fetch data from a server and put data back to a server , just like the regular API does.

The Graphql shines where you want to fetch few data (required), where REST API fetch a bunch of data, it may cause fetching too much data. API have multiple end points where graphql have one. One of the problem with graphql, it is not simple to create a graphql server, even though once it has been done ,using them is quiet simple.

Setup

With Apollo server we can build and run a graphql server, for creating route for our graphql end point can utilize the node developers favorite express module

Dependencies

To get started we need to create a folder project and then cd into the folder npm init -y for generating pacakge.json.

We also need to install few Apollo dependencies along with express.

npm i -s apollo-server apollo-core express nodemon
Enter fullscreen mode Exit fullscreen mode

nodemon help us to detect changes and automatically restart server for us.

let's open the folder in VS Code and create a index.js file ( in root directory ) and also create a script in package.json for running the server as follows

//package.json
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon ./index.js"
  },
Enter fullscreen mode Exit fullscreen mode

Mock Data

We also have users list which is used to show some mock data create users.js files with following content in the project root.

//users.js
const users =[
    {
        name:"Dev",
        role: "DBA",
        id:1
    },
    {
        name:"Jhon Doe",
        role: "Admin",
        id:2
    },
    {
        name:"Martin",
        role: "Dev",
        id:3
    }
]
module.exports = users;
Enter fullscreen mode Exit fullscreen mode

Build Apollo server

All our Apollo-graphql server code resides in index.js and we can optionally keep our schema's and resolvers in separate files, for simplicity we keep them in one file.

//index.js
const users =require("./users")
const express = require('express');
const { ApolloServerPluginLandingPageDisabled, ApolloServerPluginLandingPageGraphQLPlayground } = require('apollo-server-core');
const { ApolloServer, gql } = require('apollo-server-express');

const typDefs = gql`
   type User{
        name:String!,
        role:String!,
        id:Int
   }
   type Query{
       getAll: [User!]!
   }
   type Mutation{
       newUser(name :String!,role:String ,id:Int):User
   } 
`;
const resolvers = {
    Query: {
        getAll() {
            return users;
        }
    },

    Mutation: {
        newUser(parent, args) {
            const usr = args;
            users.push(usr);
            return usr;
        }
    }
}
const server = new ApolloServer({
    typeDefs, resolvers,
    plugins: [
        ApolloServerPluginLandingPageGraphQLPlayground({
            // options
        })
        , ApolloServerPluginLandingPageDisabled()
    ]
});

const app = express();
server.start().then(r => {
    server.applyMiddleware({ app });
    app.listen({ port: 3000 }, () =>
        console.log('Now browse to http://localhost:4000' + server.graphqlPath)

    )
})

Enter fullscreen mode Exit fullscreen mode

typeDefs

typedefs constant contains graphql type definitions, Query and Mutations, it can be a user defined objects with multiple keys. For a complete data type list refer the official documentation.

Query

As the name suggest the query is used to fetch some data, it uses the array synatax to fetch data.

Mutations

Mutations are for defining graphql part of create,update,delete functions.

Resolvers

So the first part of our graphql is done with type,query and Mutations. But this is not enough, these are structures, we have to make them working, with resolver function.

Resolvers are function to make the Query and Mutation in motion.

Play ground and Plugins

Before firing up the server, also note that the plugin array in the server setup, it replace the new Apollo play ground where you can test queries and mutations. By removing the plugin you will get the new one.

Run the project

To run the server issue npm run start and for stop the server use Ctrl + C
for good read

Discussion (0)