express.js graphql express-graphql

文档

创建应用

const l = console.log;
var express = require("express");
var graphqlHTTP = require("express-graphql");
var { buildSchema } = require("graphql");

const cats = [{ id: 1, name: "a" }, { id: 2, name: "b" }, { id: 3, name: "c" }];

var schema = buildSchema(`
  type Query {

    hello: String

    cats: [Cat]

    findCat(id: ID!): Cat
  }

  type Cat {
    id: Int
    name: String
  }
`);

// root 提供所有 API 入口端点相应的解析器函数
var root = {
  hello: () => "Hello world 233!",
  cats: () => cats,
  findCat({id}) {
    return cats.find(el => el.id === Number(id));
  }
};

var app = express();

// 根节点
app.use(
  "/graphql",
  graphqlHTTP({
    schema: schema,
    rootValue: root,
    graphiql: true
  })
);
app.listen(4000);

基本类型 String、Int、Float、Boolean 和 ID , String! 表示非空字符串,[Int] 表示一个整数列表

查询

http://localhost:4000/graphql?query={ cats { id name } }  // [Cat]

http://localhost:4000/graphql?query={ findCat(id: 2){ name } }  // Cat.name

http://localhost:4000/graphql?query={ hello } // Hello world 233!

http://localhost:4000/graphql?query={ findCat(id: 2) {name} hello } // data:{ findCat:{ "name": "b" }, hello: "Hello world 233!" }

let r = await axios.post("http://localhost:4000/graphql", {query: `{ findCat(id: ${id}) { name } hello}`});  // axios 

猜你喜欢

转载自www.cnblogs.com/ajanuw/p/9859160.html