DEV Community

loading...

#2 Adding graphql to an express server

mehaksaini11 profile image Mehak Saini ・1 min read

This post is in continuation of #1. We'll be adding graphql support to it, so let's get to it.

Navigate to your project's root directory and run the below commands. We will be using body-parser middleware to parse the incoming http requests.

npm install graphql express-graphql body-parser
Enter fullscreen mode Exit fullscreen mode

Now, go to your server.js and extract the graphqlHTTP from express-graphql using

const {graphqlHTTP}=require('express-graphql')
Enter fullscreen mode Exit fullscreen mode

Also, import the body-parser.

const bodyParser=require('body-parser');
Enter fullscreen mode Exit fullscreen mode

In express, we use the use() function in order to add middleware to our application.

app.use(bodyParser.json());
app.use('/graphql',graphqlHTTP({
}));
Enter fullscreen mode Exit fullscreen mode

Since graphql is a query language for fetching data, we need to define what type of data we are expecting.
We need to pass schema and resolvers to the graphqlHTTP method, so let's import the buildSchema property of graphql using

const {buildSchema}=require('graphql')
Enter fullscreen mode Exit fullscreen mode

In graphqlHTTP, the Query type is called RootQuery.
The resolvers property is called rootResolvers. If you're using Yoga, there are much simplified terms there. Anyways, your final code snipped should look like this.
I'm using the query name as hello and the return type as String. The exclamation sign denotes that it cannot be null.

    app.use('/graphql',graphqlHTTP({
        schema:buildSchema(`
            type RootQuery{
                hello:String!
            }
            type RootMutation{
                somemutation:String!
            }
            schema{
                query: RootQuery
                mutation:RootMutation
            }
        `),
        rootValue:{
            hello:()=>{
                return "Hello back"
            }
        },
        graphiql:true
    }))
Enter fullscreen mode Exit fullscreen mode

You may test it by visiting http://localhost:5000/graphql
image

Discussion (0)

Forem Open with the Forem app