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
Now, go to your server.js and extract the graphqlHTTP from express-graphql using
const {graphqlHTTP}=require('express-graphql')
Also, import the body-parser.
const bodyParser=require('body-parser');
In express, we use the use() function in order to add middleware to our application.
app.use(bodyParser.json());
app.use('/graphql',graphqlHTTP({
}));
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')
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
}))
You may test it by visiting http://localhost:5000/graphql
Top comments (0)