Kselax.ru

Hacker Kselax – the best hacker in the world

Menu
  • Blog
  • Contacts
  • wp plugin generator
  • English
    • Русский
Menu
graphql

How to use graphql in node.js

Posted on 14 November, 201814 November, 2018 by admin

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:

  1. quoteOfTheDay: String
  2. random: Float!
  3. 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

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Categories

  • bash (1)
  • English (9)
  • JavaScript (4)
  • node.js (22)
  • photoshop (1)
  • php (3)
  • React (9)
  • sclerotic (6)
  • Ubuntu (10)
  • Uncategorized (13)
  • Wordpress (1)

Tags

Ajax apache2 automation bash chrome-extension command line editor ejs email English English-grammar framework functions git graphql handlebars hybrid app installation javascript js linux newbie node.js node.js javascript nodemailer npm objects Performance php phpmyadmin playonlinux promise rabbitmq React react-router redis reverse-proxy session shell socket.io sublime text 3 time zones ubuntu unity webpack

Recent Comments

  • damien on How to install npm and nodejs the latest versions on ubuntu
  • Cam on How to install npm and nodejs the latest versions on ubuntu
  • Pierre on socket.io with apache as a reverse proxy on the CentOS
  • admin on How to use react-router with a few languages
  • admin on How to install npm and nodejs the latest versions on ubuntu
©2021 Kselax.ru Theme by ThemeGiant