What is GraphQL

  1. Is a query language for apis
  2. Provide an easy-to-understand set of complete descriptions of the data in your API so that clients can get exactly what they need and reduce data redundancy.
  3. In short, the back end doesn’t need to worry about what the front end gets, just returns what it can, and the front end gets exactly what it wants. For example, the back-end uses GraphQL to query several fields such as A,B,C and D of A library, and all of them can be returned. The front-end can obtain the fields it wants at will, for example, it only wants A and C. No need to communicate directly with the backend.

Basic use of GraphQL

  • Install GraphQL, here using V15.4.0
yarn add graphql@15.4. 0
Copy the code
  • Create the index.js file and start using it
  • Import graphql
const { graphql, buildSchema } = require('graphql')
Copy the code
  • Use the GraphQL Schema syntax to build a schema that represents information that the server can query
  • BuildSchema string explanation: Type Query defines the entry to the Query, where count indicates that the count field can be queried, and the Int after count indicates the type of count
const schema = buildSchema(` type Query { count:Int } `)
Copy the code
  • The Resolver that defines the schema
  • This is the logical part of the interface
const rootValue = {
	count(){
  	return 123}}Copy the code
  • Join schema and resolver and query
graphql(schema,'{count}',rootValue).then(res= >{
	console.log(res)
})
Copy the code

Graphql is used with Express

const {buildSchema} = require('graphql')
const express = require('express')
const { graphqlHTTP } = require('express-graphql')

const app = express()
Copy the code
  • Build the schema using the GraphQL Schema syntax
const schema = buildSchema(` type Query { count:Int } `)
Copy the code
  • The Resolver that defines the schema
const rootValue = {
	count(){
  	return 123}}Copy the code
  • Mount graphQL to the Express middleware
app.use('/graphql',graphqlHTTP({
	schema,
  rootValue,
  graphiql:true  // Start the graphQL IDE debugging tool in the browser
}))
Copy the code
  • Starting a Web service
app.listen(4000.() = >{
  console.log('Service already running at localhost:4000')})Copy the code
  • Use AXIos on the front end to request graphQL
axios({
 method:'POST'.// The request method for graphQL must be POST
 url:'http://localhost:4000/graphql'.data: {query:'{count}'
 }
}).then(res= >{
	console.log(res)
})
Copy the code

Graphql type

  • When you declare a schema, you need to define the entry Query of the Query, and define the fields that can be queried and the return value types in the Query
  • Graphql Built-in type String Int Float Boolean ID. If you add after type! Indicates that the field cannot be null
  • Query is strictly an object type
  • Query is the entry point for all queries
  • Query must have and cannot be repeated
  • Each type of queryable field in Query can be null
  • For object types, you need to define a type that describes the properties in the object
  • The corresponding array type must be in the form of []. Enter the type of each item in the array in brackets
  • Enum keyword enum Test is used when enumerating type declarations
type Score{
	name:String
  score:Float
}

enum Gender {
	MALE
  FEMALE
}

type User {
	name:String
  age:Int
  hobbies: [String! ] ! sores:[Score]gender:Gender
}

type Query {
	foo:String!
  count:Int
 	salary:Float
  isGood:Boolean
  userId:ID
  user:User
}
Copy the code

Fifth, modify the field

  • In addition to querying with Query, you can also modify with Mutation
  • First define the modify Schema
// Parameter objects must be defined using Input
input CreateArticleInput {
	title:String!
  body:String!
  tagList:[String]
}

input UpdateArticleInput {
	title:String!
  body:String!
}
  
type DeletionStatus {
	success:Boolean!
}

// Modify the entry pointtype Mutation { createArticle(article:CreateArticleInput):Article updateArticle(id:ID! ,article:UpdateArticleInput):Article deleteArticle(id:ID!) :DeletionStatus }Copy the code
  • Declare the modification method in resolver
createArticle({article}){
	articles.push(article)
  return articles
}

deleteArticle({id}){
	const index = articles.find(article= >article.id === id)
  articles.splice(index,1)
  return {
  	success:true}}Copy the code

Use Apollo-server

  • Apollo-server is commonly used
  • Install apollo-server and import
yarn add apollo-server

const { ApolloServer , gql } = require('apollo-server')
Copy the code
  • To define the schema
const typeDefs = gql` type Book { title:String author:String } type Query { books:[Book] } `
const books = [
	 {
    title: 'The Awakening'.author: 'Kate Chopin'
  },
  {
    title: 'City of Glass'.author: 'Paul Auster'}]Copy the code
  • Define the resolver
const resolvers = {
	Query: {books:() = >books
  }
}
Copy the code
  • Create an instance of ApolloServer and run it
const server = new ApolloServer({typeDefs,resolvers})

server.listen().then(({url}) = >{
	console.log(url)
})
Copy the code

Apollo-server with Express

  • Install express Apollo-server-Express and import it
const express = require('express')
const {ApolloServer , gql} = require('apollo-server-express')
Copy the code
  • Creating middleware
const app = express()
const server = new ApolloServer({typeDefs,resolvers})
server.applyMiddleware({app})
app.use((req,res) = >{
	res.status(200)
  res.send('Hello')
  res.end()
})
app.listen({ port: 4000 }, () = >
  console.log('🚀 Server ready at http://localhost:4000${server.graphqlPath}`))Copy the code
  • To process queries in resolver, the query method receives many parameters, and the client query parameters are in ARGS
const resolvers = {
  Query: {
    // args: query parameter of the client
    user(parent, args, context, info) {
      console.log(args)
      return users.find(user= >user.id === args.id); }}Copy the code