Get Started
npm init
cnpm i --save graphql
vim server.js
var { graphql, buildSchema } = require('graphql');
// 使用 GraphQL schema language 構(gòu)建一個(gè) schema
var schema = buildSchema(`
type Query {
hello: String
}
`);
// 根節(jié)點(diǎn)為每個(gè) API 入口端點(diǎn)提供一個(gè) resolver 函數(shù)
var root = {
hello: () => {
return 'Hello world!';
},
};
// 運(yùn)行 GraphQL query '{ hello }' 侈离,輸出響應(yīng)
graphql(schema, '{ hello }', root).then((response) => {
console.log(response);
});
node server.js
# { data: [Object: null prototype] { hello: 'Hello world!' } }
Run Server
cnpm i --save express express-graphql graphql
vim server.js
var express = require('express');
var graphqlHTTP = require('express-graphql');
var { buildSchema } = require('graphql');
// 使用 GraphQL Schema Language 創(chuàng)建一個(gè) schema
var schema = buildSchema(`
type Query {
hello: String
}
`);
// root 提供所有 API 入口端點(diǎn)相應(yīng)的解析器函數(shù)
var root = {
hello: () => {
return 'Hello world!';
},
};
var app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at localhost:4000/graphql');
node server.js
# Running a GraphQL API server at localhost:4000/graphql
curl http://localhost:4000/graphql -X POST -H "Content-Type: application/json" -d '{"query": "{ hello }"}' | json
# {
# "data": {
# "hello": "Hello world!"
# }
# }
vs RESTful
1.RESTful不足
擴(kuò)展難 單個(gè)RESTful接口返回?cái)?shù)據(jù)越來(lái)越臃腫
請(qǐng)求多 前端調(diào)用多個(gè)獨(dú)立的RESTful API才能獲取足夠的數(shù)據(jù)
2.GraphQL優(yōu)勢(shì)
- 精準(zhǔn)查詢(xún) 所得即所查
{
user(uid:1) {
uid
name
}
}
{
"data": {
"user": {
"uid": "1",
"name": "xxx"
}
}
}
- 減少調(diào)用 提高性能
{
article(aid:1) {
title
content
author {
uid
name
}
},
comment {
content,
author {
uid
name
}
}
}
代碼即文檔
參數(shù)類(lèi)型校驗(yàn)