一種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

截圖 2021-09-22 下午2.30.50.png

引入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,
  })
);

截圖 2021-09-22 下午2.48.55.png

自定義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: "內容介紹......",
    };
  },
};

截圖 2021-09-22 下午4.19.32.png

設定參數傳遞街口,及獲取指定id

Lodash

$ 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 });
  },
};

截圖 2021-09-22 下午5.34.36.png

client取得graphql請求 ⇒ GraphQL Clients