express.js graphql express-graphql

芮意
2023-12-01

文档

创建应用

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 

增加数据 和 更新数据

  type Mutation {
    createCat(cat: CreateCat): [Cat]
    updateCat(id: ID!, name: String!): [Cat]
  }

  type Cat {
    id: Int
    name: String
  }

  input CreateCat {
    name: String!
  }

var root = {
  createCat({ cat }) {
    cats.push({ id: cats.length + 1, name: cat.name });
    return cats;
  },
  updateCat({ id, name }) {
    cats.find(el => el.id == id).name = name;
    return cats;
  }
};
mutation {
  updateCat(id: 2, name: "new name") {
    name id
  }
}

mutation {
  createCat(cat:{name: "ajanuw"}) {
    name id
  }
}

// axios 实现 createCat
const query = `mutation createCat($cat: CreateCat) {
  createCat(cat: $cat) {
    name
  }
}`;
async function main() {
  let r = await axios.post("http://localhost:4000/graphql", {
    query,
    variables: {
      cat: {
        name: 'hello'
      }
    }
  });
  l(r.data.data.createCat);
}

// updateCat
const query = `mutation updateCat($id: ID!, $name: String!) {
  updateCat(id: $id, name: $name) {
    name
  }
}`;
async function main() {
  let r = await axios.post("http://localhost:4000/graphql", {
    query,
    variables: {
      id: 2,
      name: '233'
    }
  });
  l(r.data.data.updateCat);
}

获取req 对象

var schema = buildSchema(`
  type Query {
    ip(msg: String): String
  }
`);

var root = {
  ip(args, req) {
    l(args);
    return req.ip;
  }
};

query={ ip(msg: "233") }

转载于:https://www.cnblogs.com/ajanuw/p/9859160.html

 类似资料: