GraphQL
What is GraphQL ?
- query language
- usually we have one single endpoint (typically /graphql)
- uses POST because request body defines Data Structure of retrieved Data, so we are using POST for getting data
- server-side resolver analyses Request body, Fetches and Prepares and Returns Data
Why is it better than REST Api for some scenarios ?
- lets presume you have data of posts, which have
id
,title
andcontent
- imagine situation where you want to retrieve
id
andtitle
in one page andcontent
on another page - you can do two different endpoints or one endpoint loaded with query url
- both solutions arent very good or effective
- in GraphQL you can define on frontend, which data you want to retrieve from backend
npm install --save graphql express-graphql
We will create new folder graphql
under our project and under that two files schema.js
, resolvers.js
.
schema.js - here we define queries, mutations and types with which we will work in our GraphQL service
resolvers.js - here we logic which will be executed for queries
graphql/schema.js
const { buildSchema } = require('graphql');
module.exports = buildSchema(`
type TestData {
text: String!
views: Int!
}
type RootQuery {
hello: TestData
}
schema {
query: RootQuery
}
`);
graphql/resolvers.js
module.exports = {
hello() {
return {
text: 'Hello World',
views: 1234
}
}
}
app.js
const express = require('express');
const bodyParser = require('body-parser');
const { graphqlHTTP } = require('express-graphql');
const graphqlSchema = require('./graphql/schema');
const graphqlResolver = require('./graphql/resolvers');
const app = express();
// app.use(bodyParser.urlencoded()); // x-www-form-urlencoded <form>
app.use(bodyParser.json()); // application/json
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
if (req.method === 'OPTIONS') {
return res.sendStatus(200);
}
next();
});
app.use(
'/graphql',
graphqlHTTP({
schema: graphqlSchema,
rootValue: graphqlResolver,
graphiql: true
})
);
Now make POST
request from your favourite client, for example Insomnia
.
POST http://localhost:3000/graphql
{
"query": "{ hello { text views }}"
}
You should get following output:
{
"data": {
"hello": {
"text": "Hello World",
"views": 1234
}
}
}
Also if you are using graphiql: true
, you can go to http://localhost:3000/graphql
in your browser where you will have graphql playground console.