GraphQL of actual combat

1. What is GrqphQL

GraphQL is a data-oriented API query style.

GraphQL is a data-oriented API query language developed by Facebook. The client simply gives it a description, and GraphQL can assemble data from the database that matches that description and return it.

2. What problems does GraphQL solve

We generally use RESTful apis in development, which are resource-oriented. While rendering a page usually requires multiple resources, REST APIS load multiple urls when requesting multiple resources, and GraphQL gets all the data it needs in a single request.

Address pain points:

  • The interface return data format is not the caller’s (front-end) ideal

  • Multiple resources use only one request, reducing server stress

  • Data fields are controlled by the caller

GraphQL is both a query language for the API and a runtime for your data queries. 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.

Example:

Here is an example of the nuggets front page, which might be divided into these resources (article list, category list, author list)

REST API

List of articles /articles

[{title: 'xxx'.content: Content 'XXX'}]Copy the code

Categories list/Categories

[{id: '1' name: 'front end',}, {id: '2' name: 'back-end'},]Copy the code

Recommendation list /recommendationAuthor

[{id: 1.username: 'Joe'}]Copy the code

The REST interface is used to obtain the data needed for the home page. The GraphQL request needs to be sent 3 times.

GraphQL query interface/GraphQL /query

query getHomePage() { articleList($first: 0) {title content}, categoryList(){id name}, recommendationAuthorList($limit: 10) {id username},}Copy the code

Graphql only requires one request to get all the information, and the returned data format is controlled by the caller, no more, no less.

3 Important concepts of GraphQL

Here are some of the most important GraphQL concepts you can see in the GraphQL documentation.

3.1 Operation Types

The operation type can be query, mutation, or substription and describes what type of operation you intend to do.

  1. Query query
  2. Mutation change
  3. Substription is a subscription that pushes messages when data is updated

Each Graphql has a Query type, and possibly a mutation type. They define the entry point for each Graphql query.

3.2 Scalar Types

  • Int Signed 32-bit integer
  • Float Signed double - precision floating - point number
  • String Utf-8 character sequence
  • Boolean True or false
  • ID The ID scalar type identifies a unique identifier

3.3 Object Types and Fields

type Article{
	title: String
	author: [User]
}
Copy the code

Above I declared a GraphQL object type, where I declared two fields and specified the field type.

String is one of the built-in scalar types and cannot be subselected in the query.

[User] represents an array of Users in which each item is a User object.

  • Where does the User object come from?

    Use the type keyword declaration like Article

    type User {
    	name: String
    	age: Int
    }
    Copy the code
  • What is the use of declaring objects?

    When providing an entry to a Query externally through Query, we usually do it in units of one object. You can think of each object as an interface.

3.3 Input Type

Provide a change entry externally through Mutation. Sometimes you need to pass an entire object as a new object, and the previous scalar type won’t suffice.

Official website example:

4. An egg – graphql of actual combat

Before using the client side, we need to define the Schema structure on the server side.

4.1 Use scaffolding to generate Egg projects

PS: If the download is too slow, you can install the egg-init scaffolding globally before executing itegg-init --type simple --registry chinaUse Taobao image to generate items

4.2 Installing the GraphQL plug-in

  1. Execute NPM I egg-Apollo-server –save

  2. Add graphQL configuration to egg project, see egg-Apollo-server

Instead of using the egg-GraphQL plug-in, I used egg-Apollo-server

PS: config. Graphql. Subscriptions to grapql request for authentication, in this demo does not need to false

4.3 define schema

├ ─ ─ app │ ├ ─ ─ controller │ │ └ ─ ─ home. Js │ ├ ─ ─ graphql │ │ ├ ─ ─ article │ │ │ ├ ─ ─ resolver. Js │ │ │ └ ─ ─ schema. Graphql │ ├── ├─ ├─ ├─ ├─ ├─ download.txt ├─ ├─ download.txt ├─ download.txt ├─ download.txtCopy the code
  • schema.graphql

    Define GraphQL types and operations

    extend type Query {
        articleList(first: ID): [Article]
    }
    
    type Article {
        id: ID
        title: String
        content: String
        author: Author
    }
    type Author {
        name: String
        age: Int
    }
    
    extend type Mutation {
        addArticle(title: String, content: String, author: AddAuthor): Article
    }
    
    input AddArticle {
        title: String
        content: String
    }
    
    input AddAuthor {
        name: String
        age: Int
    }
    Copy the code
  • resolver.js

    Implement operation

    'use strict'; const list = [ { id: 1, content: 'aaa', title: '', author: { name: 'aaa', age: 18, }, }, { id: 2, content: 'bbb', title: '', author: { name: 'aaa', age: 18, }, }, ]; module.exports = { Query: { articleList: () => { return list; }, }, Mutation: { addArticle(root, params, ctx) { console.log(params); params.id = list.length++; list.push(params); return params; ,}}};Copy the code

4.4 graphql debugging

The browser open http://127.0.0.1:7001/graphql for debugging

PS: CSRF protection must be disabled before the test. Otherwise, POST requests sent by debugging will be blocked

On the left is the query area, where the operation statement is written. On the right is the execution result.

Query debugging

{
  articleList(first: 0){
    id
    title
    content
    author{
			name
      age
    }
	}
}
Copy the code

Change to debug

Mutation {addArticle(title: "title", content: "content", author: {name: "zhang SAN ", age: 15}){title content id}}Copy the code