一種Rest API優化
https://graphql.org/code/#javascript
$ npm install graphql express-graphql -d
引入
// app.js
const express = require("express");
const { graphqlHTTP } = require("express-graphql");
const app = express();
// graphqlHTTP 取代(req, res, next) => {}
app.use("/graphql", graphqlHTTP({}));
app.listen(4000, () => {
console.log("APP Listening on port 4000");
});
graphql須包含schema
引入graphql schema
// app.js
const { buildSchema } = require("graphql");
const schema = buildSchema(`
type Query {
hello: String,
}
`);
const root = {
hello: () => {
return "Hello GraphQL";
},
};
app.use(
"/graphql",
graphqlHTTP({
schema: schema,
rootValue: root,
// 開發階段設為true
graphiql: true,
})
);
自定義schema類型
// app.js
const schema = buildSchema(`
type Product {
id: String,
title: String,
price: Float,
content: String
}
type Query {
hello: String,
product: Product,
}
`);
const root = {
hello: () => {
return "Hello GraphQL";
},
product: () => {
return {
id: "1001",
title: "graphQL tutorial",
price: "870",
content: "內容介紹......",
};
},
};
設定參數傳遞街口,及獲取指定id
$ npm install loadsh -d
// app.js
const _ = require("loadsh");
const products = [
{
id: "1001",
title: "graphQL tutorial",
price: "870",
content: "內容介紹......",
},
{
id: "1002",
title: "graphQL2 tutorial",
price: "870",
content: "內容介紹2......",
},
{
id: "1003",
title: "graphQL3 tutorial",
price: "870",
content: "內容介紹3......",
},
{
id: "1004",
title: "graphQL4 tutorial",
price: "870",
content: "內容介紹4......",
},
];
const schema = buildSchema(`
type Product {
id: String,
title: String,
price: Float,
content: String
}
type Query {
product(id: String): Product,
}
`);
const root = {
product: ({ id }) => {
console.log(id);
// 查找products對象id是否匹配
return _.find(products, { id });
},
};
client取得graphql請求 ⇒ GraphQL Clients