directory

  • What is a GraphQL
  • What problem was solved
  • GraphQL is a simple example to get started with

What is a GraphQL

Graph + Query, a Query language for apis, has the following features

  1. Ask for the data you want no more, no less
  2. Get multiple resources with one request
  3. Describes all possible type systems

What problem was solved

1. Here’s a realistic scenario:

Before and after the end of the alignment interface has always been the special effort of a link, use the REST interface, the interface returned data format, data type (which fields, field types) are predefined back-end himself, if the returned data format is not the caller expected, as the front we can through the following two ways to solve

  • Communicate with the back end, the interface (to change the data source)
  • Those who have such experience know that it is very unrealistic to let the backend change the interface, especially when the three ends (Web, Andriod, ios) share the same set of back-end interfaces, so it is basically impossible to let the backend change the interface structure. So the front end is generally to do some interface data adaptation work

Actually we really want, what data we need, what kind of format, the back-end and in what format to give us back what kind of data structure, we are going to which fields, backend only return to us as soon as we need these fields, other all don’t return, so, the front-end and back-end decoupling, because we don’t need every day and the backend interface problems to quarrel, GraphQL is such an idea to help us solve the problem of the front and back end interconnecting interface. In the front end, we write the query directly, and the back end just returns the data of the front end query to the front end.

2. Here’s another scenario:

For information displayed on A page, info1, InfO2, and Info3, the front-end needs to request multiple interfaces: field A of interface A corresponding to Info1, field B of interface B corresponding to InfO2, and field C of interface C corresponding to Info3

// /api/user/A
{
    id: 1111.name: 'Joe'.a: 'Info1 to be displayed on current page'.b: 'b'
    // Other fields
}
// /api/order/B
{
    id: 2222.name: 'hahah'.a: 'a'
    b: 'Current page to display infO2'.// Other fields
}
// /api/system/C
{
    id: 3333.name: 'hehe'.a: 'a'
    c: 'Info3 for current page display'.// Other fields
}
Copy the code

At this time, the slightly grumpy front end will quarrel with the back end,

Front end A: “only these three fields, you still let me request three interfaces, you can not return one interface to me”, back end B: “Hey, I also want to ah, but XXXXX, so I can not change,”,… In the end so be it.

Of course, the example I gave was a very simple scenario, and the actual development process was much more complicated than this;

If use GraphQL, front end to write their own query, the page which need what to data, the backend is returned to what data, it is considering all the backend interface under the same domain, but general complex systems, the backend will be divided into different domains, user domain, domain, domain based module, pay Yi Yu, etc. This is possible even with GraphQL

Back-end C: “You see, other domains are not in my charge. If I package one for you, I need to go through XXXXX and other complicated steps to obtain other domains. This is very complicated.

There are two ways to do it,

  • You just write one more GraphQL
  • In other words, the middle layer aggregates the data of these interfaces into a GraphQL query to be returned to the front end. The middle layer takes the three interfaces of the server side and aggregates the data returned by the three interfaces into the data needed by the front end

GraphQL is a simple example to get started with

To prepare

npm i --save express  express-graphql graphql cors
Copy the code

Server code

var express = require('express');
var graphqlHTTP = require('express-graphql');
const { buildSchema } = require('graphql');
const cors = require('cors'); // To solve cross-domain problems

// To create a schema, note that:
// 1. Exclamation mark! On behalf of the not - null
RollDice accepts arguments
const schema = buildSchema(` type Query { username: String age: Int! } `)
const root = {
    username: (a)= > {
        return 'hua'
    },
    age: (a)= > {
        return Math.ceil(Math.random() * 100)}},const app = express();
app.use(cors());
app.use('/graphql', graphqlHTTP({
    schema: schema,
    rootValue: root,
    graphiql: true
}))

app.listen(3300);
console.log('Running a GraphQL API server at http://localhost:3300/graphql')
Copy the code

Client code


      
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>graphql demo</title>
</head>

<body>
    <button class="test">Get current user data</button>
    <p class="username"></p>
    <p class="age"></p>
</body>
<script>
    var test = document.querySelector('.test');
    test.onclick = function () {
        var username = document.querySelector('.username');
        var age = document.querySelector('.age');
        fetch('http://localhost:3300/graphql', {
            headers: {
                'Content-Type': 'application/json'.'Accept': 'application/json'
            },
            method: 'POST'.body: JSON.stringify({
                query: `{ username, age, }`
            }),
            mode: 'cors' // no-cors, cors, *same-origin
        })
            .then(function (response) {
                return response.json();
            })
            .then(function (res) {
                console.log('Return result', res);
                username.innerHTML = ` name:${res.data.username}`;
                age.innerHTML = ` age:${res.data.age}`
            })
            .catch(err= > {
                console.error('wrong', err);
            });
    }
</script>

</html>
Copy the code

The results

The source address

reference

  • Graphql official documentation
  • GraphQL Introduction