Graphql is a query language for an API link
graphql.js documentation link
It is usually used with express by using module express-graphql link
The sense of using at first we create a schema and in a graphql language then we create a root this is a variable that has handlers for each element in a schema. A handler is a function.
#GraphQl server
Here is an example with express
server.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
const express = require('express') const graphqlHTTP = require('express-graphql') const { buildSchema } = require('graphql') const cors = require('cors') // Construct a schema, using GraphQL schema language const schema = buildSchema(` type Query { quoteOfTheDay: String random: Float! rollThreeDice: [Int] } `) // The root provides a resolver function for each API endpoint const root = { quoteOfTheDay: () => { return Math.random() < 0.5 ? 'Take it easy' : 'Salvation lies within' }, random: () => { return Math.random() }, roolThreeDice: () => { return [1,2,3].map(_ => 1 + Math.floor(Math.random() * 6)) } } const app = express() app.use(cors()) app.use('/graphql', graphqlHTTP({ schema: schema, rootValue: root, graphiql: true, })) app.listen(4000) console.log('Running a GraphQL API server at localhost:4000/graphql'); |
graphiql: true means we can use a graphic interface and test our API, in production you have to set up it to false.
The API has 3 elements for query:
- quoteOfTheDay: String
- random: Float!
- rollThreeDice: [Int]
We can send the request with one of them or with a few
{quoteOfTheDay} or with a few {quoteOfTheDay, fandom} and we’ll get a JSON response with queried data
I did this
1 2 3 4 5 |
{ quoteOfTheDay, random, rollThreeDice } |
and got this
1 2 3 4 5 6 7 |
{ "data": { "quoteOfTheDay": "Salvation lies within", "random": 0.8872222089403614, "rollThreeDice": null } } |
This is using a graphiql interface
#GraphQL client
You can send a request by using a fetch function
client.html
1 2 3 4 5 6 7 8 9 10 |
fetch('http://localhost:4000/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' }, body: JSON.stringify({query: "{quoteOfTheDay, random, rollThreeDice}"}) }) .then(r => r.json()) .then(data => console.log('data returned:', data)) |
the end