Apollographql help use to create graphql server in Nodejs with inbuilt features. The setup was quick and easy to implement.
Node setup
As a first step we need to create a nodejs project, install dependencies, create scripts to run the project.
In the terminal CD into your project folder and run
npm init -y or npm init
Open the folder in VS Code using code . from the terminal and add following script to package.json file.
"scripts": {
"start": "nodemon src/index.js",
"start:ci": "node src/index.js"
},
Dependenciess
We need to add three dependencies to package.json and run npm install or manually install them using npm install command.
"dependencies": {
"apollo-server": "^3.6.3",
"graphql": "^16.3.0",
"nodemon": "^2.0.15"
}
Entry point
Our entry point file is index.js which setup our graphql server.
const {ApolloServer} =require('apollo-server');
const typeDefs =require('./schema');
const server = new ApolloServer({typeDefs});
server.listen().then(({url}) => {
console.log(`
Server is running!
Listening on port ${url}
Query @ http://studio.apollographql.com/dev
`);
})
In the index.js we created instance of ApolloServer , initialize it with schema which shape our data.
Schema
In the source folder create schema definition and export it.
const {gql}=require('apollo-server')
const typeDefs=gql`
type Query{
"Query to get all books"
booksForLib:[Book!]
}
type Book{
id:ID!
author:String!
title:String!
language:String
}
`;
module.exports= typeDefs;
Here we have two type , Query and Book. The Book define the book type and Query define the Output of the query.
! indicate it is non nullable object and [ ] indicates it is list of objects.
Let’s build some mock data.
In the index file add mock data and pass it to the, server object as follows
const {ApolloServer} =require('apollo-server');
const typeDefs =require('./schema');
const mocks={
Query:()=>({
booksForLib: [...new Array(5)],
}),
Book:()=>({
id:()=>'isbn_1',
author:()=>'JDoe',
title:()=>'Some title'
})
};
const server = new ApolloServer({typeDefs,mocks});
server.listen(4001).then(({url}) => {
console.log(`
Server is running!
Listening on port ${url}
Query @ http://studio.apollographql.com/dev
`);
})
Let’s run the server
npm start
Apollo port
The default port for Grapgql is 4000 , we can pass a different port to the listen method of server object.
We can use the studio / play ground to evaluate our graphql.
What is lack, live data, resolvers and we will cover it in the next post.