一天吓、GraphQL是什么扮超?
GraphQL 是一種查詢(xún)語(yǔ)言呼盆、一個(gè)執(zhí)行引擎奈惑,也是一種規(guī)范;
GraphQL 最大的優(yōu)勢(shì)是查詢(xún)圖狀數(shù)據(jù);
GraphQL對(duì)API中的數(shù)據(jù)提供了一套易于理解的完整描述,使得客戶(hù)端能夠準(zhǔn)確的獲取它需要的數(shù)據(jù)陌选,而且沒(méi)有任何冗余理郑,也讓API更容易隨時(shí)間推移而演進(jìn);
官網(wǎng):http://graphql.org
中文網(wǎng): http://graphql.cn/
二咨油、特點(diǎn):
1您炉、按需索取請(qǐng)求需要的數(shù)據(jù),比如有多個(gè)字段役电,我們可以只取需要的某幾個(gè)字段赚爵;
2、獲取多個(gè)資源,只用一個(gè)請(qǐng)求冀膝;
3唁奢、API的演進(jìn)無(wú)需劃分版本,便于維護(hù)窝剖,根據(jù)需求平滑演進(jìn)麻掸,添加或隱藏字段;
三赐纱、GraphQL 和 RestFul 的區(qū)別:
1论笔、restful 一個(gè)接口只能返回一個(gè)資源,GraphQL 一次可以獲取多個(gè)資源千所;
2狂魔、restFul使用不同的URL來(lái)區(qū)分資源,而GraphQL是用類(lèi)型區(qū)分資源淫痰;
四最楷、如何操作:
1、下載安裝Node.js待错,node和npm會(huì)一起安裝籽孙;
2、執(zhí)行命令: npm init -y (-y 的目的是為了生成package.json)火俄;
3犯建、執(zhí)行命令:npm install express graphql express-graphql -S;
4瓜客、上述命令執(zhí)行安裝成功之后适瓦,執(zhí)行js文件: node HelloWorld.js
5、訪(fǎng)問(wèn):http://localhost:3000/graphql
簡(jiǎn)單的HelloWorld 代碼:
const express = require('express');
const {buildSchema} = require('graphql');
const {graphqlHTTP} = require('express-graphql');
// 定義Schema, 查詢(xún)方法和返回值類(lèi)型
// Account 為自定義類(lèi)型
const schema = buildSchema(`
type Account { //注意: Account 是自定義的類(lèi)型
name: String
age: Int //注意:Int首字母大寫(xiě)
sex: String
department: String
}
type Query {
hello: String
accountName: String //注意:字段之間沒(méi)有逗號(hào)
age: Int
account: Account
}
`)
//定義查詢(xún)對(duì)應(yīng)的處理器
const root = {
hello: () => {
return 'Hello World';
},
accountName: () => {
return '李四';
},
age: () => {
return 18;
},
account: () => {
return {
name: '張三',
age: 19, //注意:字段之間有逗號(hào)
sex: '男',
department: '開(kāi)發(fā)部'
}
}
}
const app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true
}))
app.listen(3000);