一種用于 API 的查詢語言:GraphQL 既是一種用于 API 的查詢語言也是一個(gè)滿足你數(shù)據(jù)查詢的運(yùn)行時(shí)辙培。 GraphQL 對(duì)你的 API 中的數(shù)據(jù)提供了一套易于理解的完整描述拾积,使得客戶端能夠準(zhǔn)確地獲得它需要的數(shù)據(jù)识虚,而且沒有任何冗余丛塌,也讓 API 更容易地隨著時(shí)間推移而演進(jìn)捐寥,還能用于構(gòu)建強(qiáng)大的開發(fā)者工具胸墙。
- 安裝
- 使用
- Hello world
- Schema
- Type
- 插件
安裝
npm install graphql
Or
yarn add graphql
使用
Hello world
- 描述數(shù)據(jù):buildSchema()
- 請(qǐng)求所需數(shù)據(jù):graphql(schema, '{ hello }', root)
- 得到結(jié)果:console.log(response)
var { graphql, buildSchema } = require('graphql');
// 描述數(shù)據(jù)
var schema = buildSchema(`
type Query {
hello: String
}
`);
var root = { hello: () => 'Hello world!' };
// 請(qǐng)求所需數(shù)據(jù)
graphql(schema, '{ hello }', root).then((response) => {
// 得到結(jié)果
console.log(response);
});
Schema
Schema
是用來描述 API 的整個(gè)結(jié)構(gòu)以及結(jié)構(gòu)直接的關(guān)系,它看起來很像 JSON 數(shù)據(jù)結(jié)構(gòu)捆憎,但是在描述能力上比 JSON 更加的強(qiáng)大舅柜,并且內(nèi)置了很多類型,可以定義變量躲惰、參數(shù)等等致份。以下是一個(gè)簡(jiǎn)單的 Schema
:
type User {
id: ID
name: String!
}
Type
Schema
有完善的類型系統(tǒng),通過這些類型础拨,我們可以描述出千變?nèi)f化的數(shù)據(jù):
- 對(duì)象類型
- 字段
- 查詢&變更類型
- 標(biāo)量類型
- 枚舉類型
- ...
type Query {
user(id: ID): User
users: [User]!
}
enum Gender {
FEMALE
MALE
}
type User {
id: ID
name: String!
gender: Gender
}
-
User
是對(duì)象類型 -
name
和gender
是User
上的字段 -
String
是內(nèi)置標(biāo)量類型之一 -
String!
表示name
字段是非空的 -
[User]!
表示 User 數(shù)組氮块,它也是非空的 -
Gender
表示枚舉類型
當(dāng)然 GraphQL 可以運(yùn)行在任何后端框架或者編程語言之上,我們只會(huì)專注在類型系統(tǒng)如何描述可以查詢的數(shù)據(jù)诡宗,具體的數(shù)據(jù)實(shí)現(xiàn)由各個(gè)服務(wù)端去完成內(nèi)部的邏輯滔蝉。
插件
- express-graphql
- egg-graphql
- apollo-server
- apollo-server-express
- apollo-server-koa
- apollo-server-hapi
- apollo-server-lambda
- apollo-server-azure-functions
- apollo-server-cloud-functions
- apollo-server-cloudflare
- apollo-client
- graphql-request
- grafoo
〖堅(jiān)持的一俢〗