GraphQL入门到aws实战 - 1. 了解GraphQL


准备工作

我们使用 express将js运行为一个可被浏览器打开的网页(可以访问localhost:4000),使用 express-graphql将GraphQL的运行环境放入express容器中(访问的内容是GraphQL的测试环境)。

const express = require("express");
const { graphqlHTTP } = require("express-graphql");

const app = express();
app.use(
  "/graphql",
  graphqlHTTP({
    // 交互式地访问GraphQL
    graphiql: true,
  })
);
app.listen(4000);

了解graphql

graphql的宗旨是需要的数据都要,不需要的数据一点也不要,即它可以查询多个表中的每一项信息。在传统的Rest中,如果我们需要2个表的信息,我们可能需要请求2个Rest API然后自己拼接信息,这会导致浪费大量的网络带宽请求不需要的资源。另一种解决方案是后端增加一个Rest API接口,后端进行数据库的连表查询。

graphql就是为了解决这个痛点而生的,只要是graphql的服务器,前端需要什么数据就拿什么数据。

定义有什么数据

和传统数据库类似的,需要有个建表语句。graphql也要定义数据类型。

const { buildSchema } = require("graphql");
const schema = buildSchema(`
    type Account{
      age: Int
      name: String,
      todos: [String]
    }
    type Query {
        hello: String
        account: Account
    }
`);

最重要的是第8行的Query,它定义了前端可以执行查询语句。它代表前端查询hello的话会返回一个string,而查询account的话会返回一个Account对象。Account对象有3个字段:年龄(int类型)、名字(string类型)和待做的事(string数组)

模拟数据库存储的数据

没有花里胡哨,简单易懂的js。

const root = {
  hello: () => {
    return "hello world";
  },
  account: () => {
    return {
      age: 18,
      name: "jimmy",
      todos: ["eat", "sleep"],
    };
  },
};

整合

将上述的所有代码整合,形成一个完整的hello.js如下:

const { buildSchema } = require("graphql");
const express = require("express");
const { graphqlHTTP } = require("express-graphql");
const schema = buildSchema(`
    type Account{
      age: Int
      name: String,
      todos: [String]
    }
    type Query {
        hello: String
        account: Account
    }
`);

const root = {
  hello: () => {
    return "hello world";
  },
  account: () => {
    return {
      age: 18,
      name: "jimmy",
      todos: ["eat", "sleep"],
    };
  },
};
const app = express();
app.use(
  "/graphql",
  graphqlHTTP({
    schema: schema,
    graphiql: true,
    rootValue: root,
  })
);

app.listen(4000);

hello.js存储的路径下,使用node init -y初始化并使用npm install graphql express express-graphql -S 安装依赖。最后,使用 node hello.js运行,访问localhost:4000/graphql即可。


文章作者: VsKendo
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 VsKendo !
  目录