What is graphql
When you first see GraphQL, you’re kind of like, oh, this is… This!!!! What! Yao! 🙉 but once I accepted his setting, I felt that he was somewhat similar to TS. Without further ado, get to work!
The official website explains:
GraphQL is a query language for apis, a server-side runtime that executes queries using a type based system (defined by your data). GraphQL isn’t tied to any particular database or storage engine, but relies on your existing code and data. A GraphQL service is created by defining a type and the fields on that type, and then providing parsing functions for each field on each type.
Simple: Ask exactly what you want. Give what you want, format res and REq
Why graphQL 👏
Traditional restful
- Data redundancy and too many requests
- If we want to get information about a user, we may only have id and nickname at first, but as our requirements change, the user may include more and more fields, such as age, gender, avatar, experience, level, and so on. GET user information interface. Even if we only want one or two pieces of information about a user, through this API, we will GET the whole information about that user.
- If we want to get a list of users, we actually need to call multiple separate apis to get enough data, or another interface to add trouble to the back end
- Trouble in changing restful interfaces
- If you want to change an API in restful environment, whether you want to add or delete the value field, change the range of the value field, or increase or decrease the number of apis, change the API URL, it is easy to become a broken behavior, and both sides need to change
Graphql benefits
- Reduce data and request redundancy
- Schema format
- The format and types of RES and REQ are limited by defining schema
- Interface checking
- As shown above, no additional tools are required to validate the Query
- Interface changes, maintenance and documentation
- The client only needs to specify the desired data, not the specific format. Server, as long as the data provided is the parent set of the requester, no matter how they vary, does not need to be influenced by the other party.
🚀 Syntax overview
Operation type
Query query
: Get data (parameters)Mutation change
: Perform operations on data (add, delete, modify)Substription subscription
: Notification push when data changes
Types of query (response)
- Object type: Type defined by the user in the schema
typeObj{name:String, Account :String, age:Int, salary(city:String):String}//Obj is the defined typeCopy the code
- Scalar types:
a.String
UTF‐8 character sequence.
b.Int
Signed 32-bit integer.
c.Float
Signed double precision floating point value.
d.Boolean
True or false.
e.ID
The ID scalar type represents a unique identifier, usually used to retrieve an object or as a key in the cache. The ID type is serialized in the same way as String; However, defining it as an ID means that it does not need to be human-readable.
F. It can also be defined as follows:
scalar Date
Copy the code
- Enumeration types: a. Verify that any parameter of this type is an optional value. B. Communicate with the type system that a field is always one of a finite set of values.
enum Gender {
MAN
WOMAN
}
Copy the code
- Interface types: a. An interface is an abstract type that contains fields that an object type must contain to implement the interface.
interface Character { id: ID! name: String! friends: [Character] appearsIn: [Episode]! } // This means that any type that implements Character should have these fields, with corresponding parameters and return types.Copy the code
B. Inheritance and extensibility
type Human implements Character {
id: ID!
name: String!
friends: [Character]
appearsIn: [Episode]!
starships: [Starship]
totalCredits: Int
}
type Droid implements Character {
id: ID!
name: String!
friends: [Character]
appearsIn: [Episode]!
primaryFunction: String
}
Copy the code
Input Type (Request)
input ReviewInput {
stars: Int!
commentary: String
}
Copy the code
Exception handling
GraphQL query error
- Feature: The return code is 200, and the returned data field is NULL. The returned data object contains an errors field
- Example: Query Document syntax error
HTTP error
- Feature: The return code is 4XX or 5XX, and the return body has message and documentation_URL fields
- Example: request body JSON parsing error; The Access token is invalid
Network anomalies
- Characteristic: The fetch method throws an exception
- Example: Cell phone has no Internet signal
JSON parsing exception
- The response.json () method throws an exception
- Example: As the fetch method will immediately resolve and the parsing process of Response.json() will start once it receives the returned information, if the network is interrupted suddenly and all the returned bodies cannot be received, the parsing of Response.json() will fail and an exception will be thrown
Graphql disadvantage
- Each different type of request has to write a return scheme
- 200 returns null if not found
😈 epxress + graphql small practice
const express = require('express')
const { buildSchema } = require('graphql')
const graphqlhttp = require('express-graphql'// Define shema queries and types const schema = buildSchema('type Obj{
name:String,
account:String,
age:Int,
salary(city:String):String
}
typeQuery{ hello:String age:Int account:Obj getName(class:Int!) :[String] getAccount(user:String):Obj accounts:[Account] } input AccountInput{ name:String, age:Int, }type Account{
name:String,
age:Int,
}
typeMutation{ createAccount(input:AccountInput):Account updateAccount(id:String,input:AccountInput):Account } `) const db = Const root = {accounts: () => {let arr = []
for (let i in db) {
arr.push(db[i])
}
return arr
},
hello: () => {
return 'hello world'
},
age: () => {
return 123
},
createAccount({ input }) {
db[input.name] = input
return db[input.name]
},
updateAccount({ id, input }) {
const obj = Object.assign({}, db[id], input)
db[id] = obj
return obj
},
getName({ class: classNo }) {
const obj = {
11: ['gsc11'.'gsc22'.'gsc33'],
22: ['gsc2'.'gsc44'.'gsc66']}return obj[classNo]
},
getAccount({ user }) {
const name = user;
const age = 22;
const account = '123';
const salary = ({ city }) => {
if (city == 'bj' || city == 'sh' || city == 'gz') {
return '10k'
}
return '6k'
}
return {
name,
age,
account,
salary
}
},
account: () => {
return {
name: 'gsc',
account: '123',
age: '18s'
}
}
}
const app = express()
app.use('/graphql', graphqlhttp({
schema: schema,
rootValue: root,
graphiql: true}))// Public folder for accessing app.use(express.static()'public'))
app.listen(3000)
Copy the code