Do not understand the place or have a lot of, share the experience of learning, if there is a mistake, but also hope you to make it

What is a GraphQL

GraphQL is an open source API query language of Facebook. It provides a complete description of the query data. The client can accurately obtain the required data without any redundancy

I want to get the todoList set. Each element in the set contains the _ID,content, and completed fields. The data returned by the server is the data I need for the request

The basic concept of GraphQL – Query

    type todo {
        _id: ID!
        content: String!
        completed: Boolean!
    }
Copy the code
  • todoThat means this is a GraphQL object
  • _id,contentandcompletedistodoIn the field,ID,String,BooleanBoth types are built-in to GraphQL
  • String!Indicates that the value of this field isStringType and cannot be empty

Next, create a query

    type Query {
        todoList: [todo]!
    }
Copy the code
  • QueryandMutetionBoth are keywords for GraphQL, one for query and one for change, which are used hereQueryA query is created
  • [todo]!According to fieldtodoListThe value of is one defined abovetodoArray of type,[todo]!Indicates that the field is either an empty array[]Or the element is zerotodoAn array of[todo,todo,...]

Data types in GraphQL

  • Int: a signed 32-bit integer
  • Float: a signed double floating point value
  • String: UTF‐8 string
  • Boolean: Boolean
  • ID: unique identifier in serializationStringUnreadable to humans

You can also customize types

Build the GraphQL server

Now that you know the query, let’s create a GraphQL server. I’m using Apollo GraphQL, which is a very complete GraphQL implementation, including client and server. The Node server uses KOA

First create a project, then install the following dependencies

npm i -S apollo-server-koa graphql koa

Create the app.js file in the root directory

const Koa = require("koa");
const { ApolloServer } = require("apollo-server-koa");

const { gql } = require("apollo-server-koa");

// Define the graphQL method to get data from the server
const typeDefs = gql` type todo { _id: ID! content: String! completed: Boolean! } type Query { todoList: [todo]! } `;

const server = new ApolloServer({
  // GraphQL DocumentNode defined using GQL tags and strings
  typeDefs,
  / / open the mock
  mocks: true
});

const app = new Koa();

// applyMiddleware connects the GraphQL service to the KOA framework
server.applyMiddleware({ app });

app.listen({ port: 4000}, () = >console.log('🚀 Server ready at http://localhost:4000${server.graphqlPath}`));Copy the code

Then run the node app. Js, you can see it on the http://localhost:4000/graphql Apollo server provides the playground

The query

{
  todoList{
    _id
    content
    completed
  }
}
Copy the code

Enter the top query on the left, and the mock data will appear on the right

Add resolvers

Resolvers is a resolver used to resolve typeDefs queries. It is a mapping with a key of type name and a value of function. Add resolvers in app.js

// ...
// Create a data
const data = [
  {
    _id: "5ca16ed7c39e5a03d8ad3547".content: "html5".completed: false
  },
  {
    _id: "5ca16ee0c39e5a03d8ad3548".content: "javascript".completed: false
  },
  {
    _id: "5ca16ee5c39e5a03d8ad3549".content: "css".completed: false}];// resolvers
// todoList is a function that returns data
// You can write asynchronous functions for real database queries
const resolvers = {
  Query: {
    todoList: (a)= > data
  }
};
// Add resolvers and cancel mocks
const server = new ApolloServer({
  typeDefs,
  resolvers,
});

const app = new Koa();
/ /...
Copy the code

Query again, and the result returned is the data of data

The basic concept of GraphQL — Mutation

Mutations can correspond to CRUD in the REST API, and a simple Mutation is added to typeDefs as follows

    type updateResponse {
        success: Boolean!
        todoList:[todo]!
    }
    type Mutation {
        addTodo(content: String): updateResponse!
    }
Copy the code

This is a Mutation operation that adds a todo item and returns an updateResponse object

  • addTodo(content: String)Receive a forStringParameter of type
  • updateResponseThe value includes a key namesuccessA value ofBooleanAnd a key nametodoListA value oftodoAn array of

Execute in playground

Modify the resolvers

const resolvers = {
    Query: {
        todoList: (a)= > data
    },
    Mutation: {
        addTodo: (_, { content }) = > {
            console.log(content);
            data.push({
                _id:Math.random().toString(36).substring(3),
                content,
                completed:false
            });
            return { success: true.todoList:data }; }}};Copy the code

See Resolver Type signature for specific parameters in the function

perform

mutation{
  addTodo(content:"css"){
    success
    todoList{
      _id
      content
      completed
    }
  }
}
Copy the code

Mutation indicates that this is an mutation operation named addTodo that receives an argument named Content of type String and returns success and todoList

You can see the arguments from the console in nodeJS

Use GraphQL on the client side

React, React-Native, Vue, Augular, Native-ios… Etc used in creact-React-app

Although the official Query and Mutation components in component mode are provided, I still use the method mode directly written in JS and the Client API reference in the learning process

Install dependencies in the create-React-app project

npm install apollo-boost react-apollo graphql --save

Create client.js and add proxy to package.json

import ApolloClient from "apollo-boost";
const Client = new ApolloClient();
const getList = async() = > {return await Client.query({
        query: gql` { todoList { _id content completed } } `
    });
};
const add = async content => {
    return await Client.mutate({
		// Parameter,content corresponding to the following $content
        variables: { content },
        mutation: gql` mutation add($content: String!) { addTodo(content: $content) { success todoList{ _id content completed } } } `})};export {getList,add};
Copy the code

Provide IDE support

I used WebStorm, which is a very powerful integrated IDE, to search and install JS GraphQL in plugins

exportschema.json

  • npm install -g apollo-codegen
  • Client root directoryapollo-codegen introspect-schema http://localhost:4000/graphql --output graphql.schema.json

Webstrome will provide very smart graphQL code formatting and completion

Demo

In the process of learning, I wrote two demos. The mongodb used by the database has never been used before, and I also learned it now. Many of them do not understand…

The client

The service side

There are still a lot of things I don’t understand, and the documents are in English and very complicated, so there is a long way to go

Companies are definitely not using GraphQL, rest API is a problem, alas…