• 🏆🏆🏆 Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
  • 📣📣 welcome to give your thumbs up and follow!!

preface

There are dozens of articles on what GraphQL is, some long and some short, but at its core, it’s a query language and, by extension, an API query language.

Some of you might say, what? API can still check? Isn’t an API for calling? Yes, that’s the power of GraphQL, to quote the official documentation:

ask exactly what you want.

Today we will take a look at how GRAPQL is used.

The scenes encountered in daily work

  1. A detail page in which certain fields are no longer displayed during the iteration, but the interface still returns the data and the front end does not use the fields, and over time there are more and more such fields
  2. As for the data return format, the front end and back end need to communicate for a long time, before a mutually accepted situation
  3. Because it is a low-level public interface, the backend can not be arbitrarily modified, resulting in the actual use of less than half of the fields in the front end of some interfaces
  4. The format of the interface field is uncertain and changes frequently

How to do?

Graphql solves these problems

define

  • GraphQL is both a query language for apis and a runtime for your data queries. It is developed and open source by Facebook.
  • GraphQL provides an easy-to-understand set of complete descriptions of the data in your API, enabling a client to get exactly what it needs without any redundancy, making it easier for the API to evolve over time, and for building powerful developer tools.
  • GraphQL isn’t tied to any particular database or storage engine, but relies on your existing code and data.

The specific use

Use in detail

My understanding:

  1. Graphql is actually a layer of services where you can reorganize or modify the data structure. In addition, the developers of this layer can be either the back-end or the front-end. graphql.cn/code/
  2. As the middle layer, it can be done between the client and the server, as a service, or directly on the server, with a choice of tool libraries for different languages
  3. The great thing about GraphQL is not only data assembly, but also the ability for clients to get exactly the data structure they want, no more, no less, and the data format is completely determined.
  4. Visual data query

Official features:

  • Declarative data retrieval (you can query the API) : Declarative data query brings the exact return of the interface, and the server returns JSON data with the same structure in the data query format, with real flexibility for the client.
  • A microservice exposes only one GraphQL layer: A microservice exposes only one GraphQL endpoint, and the client requests the corresponding data only through this endpoint on demand, without additional interface definition.
  • Transport layer independent, database technology independent: more flexible technology stack selection, for example, we can choose mobile device friendly protocols, minimize the amount of data transmitted over the network, and optimize the application at the network protocol level.

Graphql supports the following operations:

  • Query: A basic Query that retrieves data.

  • Mutation: Supports data addition, deletion, and modification.

Mutation {insert(title: "111" Genres: "JHSJ" rating: 9.4 theater: 2) {id}}Copy the code
  • Subscription: Used to listen for changes in data and push messages to each other using protocols such as Websocket.

Graphql data model

To use GraphQL, you need to define the GraphQL data model for each interface, and to define the data model, you need to support a Schema syntax, namely the GraphQL syntax, which will not be described here. It is roughly written as follows:

  • A bit like defining a database, we need to show the data structure that declares each field
  • Graphql is written differently. There are several ways to write it, but this is just one way to write it, GraphQLSchema
let MovieType = new GraphQLObjectType({
    name: 'MovieType',
    fields: {
        user_name: {
            type: GraphQLString
        },
        company: {
            type: GraphQLString
        },
        user_id: {
            type: GraphQLString
        },
        got_digg_count: {
            type: GraphQLInt
        },
        got_view_count: {
            type: GraphQLInt
        },
        description: {
            type: GraphQLString
        }
    }
})
Copy the code

Another way to write it is buildSchema

const schema = buildSchema(` type SignType { accessid: String, dir: String, expire: Int, host: String, policy: String, signature: String } type CommonType { id: String } type Query { hello: String, sign(cate: String!) : SignType common(type: String, city_id: String, order_id: String): CommonType } `);Copy the code

Graphql can solve all of the scenarios mentioned above:

  1. If the front end wants data, the front end decides by itself. According to the parameters passed, it can decide the data to be returned, with high flexibility
  2. How does the front end aggregate the interface itself, using GraphQL, and define its own return structure
  3. Graphql defines the data structure without changing it

Graphql shortcomings

  1. At present, it is not popular, because the implementation cost is high, especially for some companies with clear division of labor at the front and back end, or with mature back-end architecture, it is almost impossible to promote
  2. There may be query redundancy
  3. There are too few official, mature solutions

use

Step 1: Initialize a project. We don’t have to do much configuration. We’re just testing graphQL, so when you create a project, just press Enter

 npm init
Copy the code

Step 2: Download graphQL related, because we want to sneak graphQL in Node and use the Framework Express, so we need Express and Express-GraphQL

yarn add graphql express express-graphql
Copy the code

Step 3: Download Babel related, because I may need some ES6 writing to write graphQL (not for now)

yarn add @babel/cli @babel/core @babel/node
Copy the code

Step 4 configure package.json

// nodemon If not, download "dev": "nodemon index.js --exec babel-node --presets @babel/preset-env", "test": "echo "Error: no test specified" && exit 1" }Copy the code

Step 5 create an index.js and start a service with Express: http://localhost:5000

import express from 'express';
const app = express();
app.use((req, res) => {
    res.send('welcome');
})
app.listen(5000);
Copy the code

Now we are ready to configure the GraphQL

// index.js import { graphqlHTTP } from 'express-graphql'; import GraphqlSchema from './GraphqlSchema'; const app = express(); Use ('/graphql', graphqlHTTP({schema: GraphqlSchema, graphiQL: true,}),); app.listen(5000);Copy the code

Create a new graphqlSchema.js file and configure the graphQL schema

import { graphql, GraphQLSchema, GraphQLObjectType, GraphQLString, GraphQLList, GraphQLInt } from 'graphql'; var schema = new GraphQLSchema({ query: new GraphQLObjectType({ name: 'RootQueryType', fields: { hello: { type: GraphQLString, resolve() { return 'world'; },}}})}); export default schema;Copy the code

Start command:

npm run dev

Enter in your browser: http://localhost:5000/graphql can start graphql server, enter the query at the same time, visualization query, as shown in figure

We can also do some more complex data configuration

// GraphqlSchema.js let HelloType = new GraphQLObjectType({ name: 'HelloType', fields: { name: { type: GraphQLString }, age: { type: GraphQLInt }, phone: { type: GraphQLString } } }) var schema = new GraphQLSchema({ query: new GraphQLObjectType({ name: 'RootQueryType', fields: { hello: { type: new GraphQLList(HelloType), resolve() { return [ { name: 'tom', age: 18, phone: '323243434' }, { name: 'jerry', age: 10, phone: '1123333' }, { name: 'hahah', age: 48, phone: '222233444' } ]; }}}})});Copy the code

Refer to the article

Github.com/chentsulin/…

Why did I give up Restfull to embrace GraphQL?

Graphql – front end