This is the first part of the series GraphQL in pieces.
A passionate programmer always adds new skills to his arsenal, besides enhancing his existing skills. Learning a new trending skill is like increasing a worth.
GraphQL is a structured query language, that helps us query only required data from a server. Less request on server means less cost.
Our today's task is to run a GraphQL server and query the data via GraphiQL (in-browser IDE for exploring GraphQL).
Before starting the series let's set our realistic end goal.
So in the next two months, our goal is to build a GraphQL powered API with authentication and authorization for real-world application.
Let's begin
Open your terminal and create a folder on your desired location mkdir folderName
go to your folder using command cd folderName
I am assuming you have nodejs installed and familiar with the basics of terminal.
Now we have to create a package.json
file, the same as we do while we create a rest API.
We can create package.json
file using the command npm init
I run npm init -y
to skip the questions.
Now we have to install three dependencies
npm i express express-graphql graphql
Create the file server.js
on root, some name it index.js
, it's up to you.
Now require the packages we just installed in server.js
file.
const { buildSchema } = require('graphql')
We just pull out buildSchema
method out of graphql
using ES6 destructuring, it will help us create the schema.
const { graphqlHTTP } = require('express-graphql')
This package helps us to create a graphql http server
with express.
we also initialize express
just like we do while writing rest API.
const app = express()
This is how our code looks like now.
const express = require('express')
const { buildSchema } = require('graphql')
const { graphqlHTTP } = require('express-graphql')
const app = express()
Creating the Schema
Query is for reading data. If we define a schema with a keyword query
we can't mutate it, means we can't perform edit, update or delete actions.
We have used an exclamation mark with name: String!
it means name is required, this can't be null.
const schema = buildSchema(`
type Query {
name: String!,
designation: String
}
`)
Resolver Function
GraphqQL schema needs to have a resolver function for each field, resolver function returns the result for that particular field it defines for.
I want whenever I query name, it should always return John. For that, I need to define a resolver function. If I won't, a default resolver will be set and that would be null. In case, if the field is required, like we have required name, and we didn't write a resolver function for that, GraphiQL
will give us an error.
Just keep in mind Resolver also returns promise. We will see the implementation once we will be connected to database and ready to fetch the data.
const rootValue = {
name: () => 'John',
designation: () => 'Junior MERN Stack developer',
}
Create the server
app.use('/graphql', graphqlHTTP({
schema,
rootValue,
graphiql: true,
}))
graphqlHTTP
function accepts several options, for simplicity we defined only 3.
- The first one is the schema we defined earlier
- Second is resolver with named
rootValue
, this is an object, provides a resolver function for each API endpoint, - The third one is graqphiql to test our
API
end points.
In JavaScript, if the key values are same we write it only once, so instead of writing {schema: schema}
we wrote it only once {schema}
, this makes our code cleaner.
Let's run the server and listen to port 5000 using listen()
method express provides us that returns http.Server
function.
We provide a port as a first parameter and in callback we just console.log()
We are done, it's time to execute the code. For that, we will run a command node server.js
in our terminal. You will get the log
Server is running at localhost:5000/graphql
Complete Code
const express = require('express')
const { buildSchema } = require('graphql')
const { graphqlHTTP } = require('express-graphql')
const app = express()
const schema = buildSchema(`
type Query {
name: String!,
designation: String
}
`)
const rootValue = {
name: () => 'John',
designation: () => 'Junior MERN Stack developer',
}
app.use('/graphql', graphqlHTTP({
schema,
rootValue,
graphiql: true,
}))
const port = process.env.PORT || 5000
app.listen(port, () => console.log(`Server is running at localhost:${port}/graphql`))
In next article, we will learn about mutation
and relation between queries, and simplify our code using Apollo Server
with better graphql playground.
Your assignment is to execute all the code once on your own. Type the code, instead of copy, so you become familiar with the syntax. Go ahead, it will not take more than 5 minutes.
Top comments (1)
How so simple, waiting a series in this 👍