Back to blog
2024年4月24日
3 min read

graphQl

graphQl基础

1. 介绍

  • 是Facebook开发的一种数据查询语言,并于2015年公开发布,是rest API 的替代品
  • 是一种用于API的查询语言也是一个满足你数据查询的运行是

中文网:http://graphql.cn

2. 特点

  1. 请求需要的数据,不多不少
  2. 获取多个资源,只用一个请求
  3. 描述所有可能类型的系统,便于维护,根据需求平滑进演,添加或隐藏字段

3. 基本参数类型

  • 基本类型: String、Int、Float、Boolean、ID,可以在shema声明的时候使用
  • [类型]:代表数组,例如: [Int] 代表整型数组

4. 参数传递

  • 合js一样,小括号内定义形参,但注意:参数需要定义类型
  • ! 代表参数不能为空
type Query {
 rollDice(numDice: Int!,numSides:Int):[int] // 表示返回值为Int类型的数组
}

// numDice不能为空

案例:

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

const schema = buildSchema(`
type Account {
  name: String
  age: Int
  sex: String
  salary(city:String): Int
}
type Query {
  getClassMess(classNo:Int!):[String],
  account(username:String): Account
}
`)

const root = {
  getClassMess({classNo}){
    const obj = {
      31: ['张三','李四','王五'],
      61: ['kk','yy','ww']
    }
    return obj[classNo]
  },
  account({username}){
    const name = username
    const age = 20
    const sex = '男'
    const salary = ({city})=>{
      if(city === '深圳'|| city ==='北京'){
        return 10000
      }
      return 3000
    }
    return {
      name,
      age,
      sex,
      salary
    }
  }
}

const app = express()

app.use('/graphql', graphqlHTTP({
  schema:schema,
  rootValue: root,
  graphiql:true
}))

app.listen(3000)

输入时如下:

// 输入查询的值
query{
  account(username:"zz"){
    name,
    age,
    salary(city:"深圳")
  }
}

// 返回的值
{
  "data": {
    "account": {
      "name": "zz",
      "age": 20,
      "salary": 10000
    }
  }
}

5. 如何在客户端访问grapql clients

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<button onclick="getData()">获取数据</button>
<script>
  function getData(){
    let query = `
    query Account($username:String){ // 变量引入需要使用$
      account(username: $username){
        name
        age
        sex
        salary(city: "深圳")
      }
   }`
    const variables = {
      username: '李四' // 与上方一致
    }
    fetch('/graphql',{
      method: 'POST',
      headers: {
        'Content-type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify({
        query,
        variables: variables
      })
    }).then(res=>{
      return res.json()
    }).then(res=>{
      console.log(res)
    })
  }
</script>
</body>
</html>

6. 使用Mutations修改数据

案例

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

/**
 * input 表示输入,type 表示查询
 */
const schema = buildSchema(`
input AccountInput{ // 定义一个输入类型
  name: String
  age:Int
  sex:String
  department:String
}
type Account{ // 定义一个查询类型
  name: String
  age:Int
  sex:String
  department:String
}
type Mutation {
  createAccount(input:AccountInput):Account
  updateAccount(id:ID!,input:AccountInput):Account
}
type Query{ // 查询
  account: [Account]
}
`)

const fakDb = {}
const root = {
  account(){
    let arr = []
    for(const key in fakDb){
      arr.push(fakDb[key])
    }
    return arr
  },
  // 相当于数据库保持
  createAccount({input}){
    fakDb[input.name] = input
    console.log(fakDb)
    // 返回保持结果
    return fakDb[input.name]
  },
  updateAccount({id,input}){
    // 相当于更新数据库
    const update = Object.assign({},fakDb[id], input)
    fakDb[id] = update
    return update
  }
}

const app = express()

app.use('/graphql', graphqlHTTP({
  schema:schema,
  rootValue: root,
  graphiql:true
}))

app.use(express.static('public'))

app.listen(3000)

输入数据

mutation{ // 插入数据
  createAccount(input:{
    name: "kkk",
    age: 20,
    sex:"男",
    department:"看牛"
  }){
    name
  }
}
query{ // 查询数据
  account{name,age,sex}
}

mutation{ // 更新数据
  updateAccount(
    id:"kk", // 传参
    input:{
      age:30,
      sex:"女"
    }
  ){ // 返回值
    name,
    age,
    sex
  }
}

7. 使用GraphQLObjectType定义type和query

定义type

类型1

定义query

类型2

  1. args: 表示参数
  2. resolve: 返回值,第一个参数可以不用管,第二个参数为解构出来的参数