GraphQL

276 阅读2分钟

简介

graphql.webp

  • GraphQL是Facebook开发的一种数据查询语句,并于2015年公开发布,是RESTful的替代品
  • GraphQL 是一种面向数据的 API 查询风格
  • 传统的 API 拿到的是前后端约定好的数据格式,GraphQL 对 API 中的数据提供了一套易于理解的完整描述,客户端能够准确地获得它需要的数据,没有任何冗余,也让 API 更容易地随着时间推移而演进,还能用于构建强大的开发者工具。

GraphQL特点

  • 请求需要的数据,不多不少,例如:account中有name,age,sex,department等,可以只取得需要的字段。
  • 获取多个资源,只需要一个请求
  • 描述所有可能类型的系统,便于维护,根据需求平滑演进,添加或隐藏字段

GraphQL和RESTful对比

RESTful一个接口只能返回一个资源,GraphQL一次可以获取个资源 RESTful用url来区分资源,GraphQL用类型来区分资源

demo (express/GraphQL)

import express from 'express'
import {graphqlHTTP} from 'express-graphql'
import {buildSchema} from 'graphql'

const app = express()

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

type User = {
    name:string;
    age:29;
    sex:string;
    salary(city:String):number
}

const rootValue = {
    hello: () => {
        return `hello world`
    },
    account: ({id}:{id?:number}) => {
        const users:{[key:string]:User} = {
            1:{
                name: 'jingsong',
                age: 29,
                sex: '男',
                salary:()=>{
                    return 111
                }
            }
        }
        return users?.[id??0] ?? {}
    },
    getClassMates: ({classNo}: { classNo?: string }) => {
        const mates:{[key:string]:string[]} = {
            31: ['小明', '小红'],
            30: ['张三', '李四']
        }
        return mates?.[classNo??''] ?? []
    }
}

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

app.listen(3000, () => {
    console.log('listening 3000')
})

参数类型

  • 基本类型:String Int Float Boolean ID,可以在schema声明的时候直接使用。
  • [类型]代表数组,如:[Int]代表整形数组

参数传递

  • 和js参数一样,小括号内定义形参,但是注意:参数需要定义类型
  • !(叹号)代表参数不能为空
type Query {
    rollDice(numDice:Int!,numSides:Int):[Int]
}

客户端调用

const getData = async ()=>{
    return  await fetch('/graphql',{
        method:'POST',
        headers:{
            'Content-Type':'application/json',
            'Accept':'application/json'
        },
        body:JSON.stringify({
            query:`
            query Account($id:Int, $city:String) {
                account(id:$id){
                 name
                 age
                 salary(city:$city)
                }
            }
            `,
            variables:{id:1,city:'shanghai'}
        })
    })
}

Mutations

// 未完待续