apollo-server 提供了一个用于构建 GraphQL API 的框架 构建 GraphQL API 需要实现 2 个组件:

  • Schema :系统中存在哪些类型以及这些类型允许进行哪些操作。
  • Resolvers:如何加载类型的各个属性。

Schema and Resolvers

使用 GraphQL 模式和解析器,您可以使用 Apollo 定义只读 API,首先 GraphQL 模式是一个字符串,它定义了 API 返回的每种类型以及 API 允许的每个操作。 例如下面的 GraphQL 模式定义了一个查询操作, getCount(),返回一个类型的对象 CountResult

const schema = `
  type Query {
    getCount: CountResult
  }

  type CountResult {
    count: Int
    time: Float
  }
`;

在 GraphQL 模式中, Query type 是特殊的:它列出了服务器允许的所有查询(只读操作)。Resolvers 允许您实际实现 getCount() 功能。下面的示例展示了如何使用上述模式启动 Apollo 服务器,并使用 Axios 发出 HTTP 请求:

const { ApolloServer, gql } = require(apollo-server);

let count = 0;

// The `gql()` function parses the schema
const schema = gql(`
  type Query {
    getCount: CountResult
  }

  type CountResult {
    count: Int
    time: Float
  }
`);

// Resolvers define how the actual operations are implemented.
// The `Query.getCount()` resolver defines what happens when
// you call `getCount()`, and the `Query.CountResult` resolvers
// define how to transform the individual properties.
const resolvers = {
  Query: {
    getCount: () => ({ count, time: Date.now() })
  },
  CountResult: {
    count: obj => obj.count,
    time: obj => obj.time
  }
};

const server = new ApolloServer({ typeDefs: schema, resolvers });
const handle = await server.listen();

// Make a request to the Apollo server. GraphQL requests are
// just plain old HTTP requests.
const axios = require(axios);
const { data } = await axios.post(handle.url, {
  query: `
    { getCount { count, time } }
  `
});

data.data; // { getCount: { count: 0, time: 1581442587371 } }

Mutations

以前的 Apollo 服务器是只读的。 它只允许您获取当前 count,而不是增加它。 在 GraphQL 中,修改数据的操作称为 Mutations。就像 QueryMutation 是一种特殊类型,它列出了您的 API 允许的每个 Mutations。

const schema = `
  type Query {
    getCount: CountResult
  }

  type Mutation {
    increment: CountResult
  }

  type CountResult {
    count: Int
    time: Float
  }
`;

在 Apollo 中,Mutations 只是解决 Mutation 如下图所示。

const { ApolloServer, gql } = require(apollo-server);

let count = 0;

const schema = gql(`
  type Query {
    getCount: CountResult
  }

  type Mutation {
    increment: CountResult
  }

  type CountResult {
    count: Int
    time: Float
  }
`);

const resolvers = {
  Query: {
    getCount: () => ({ count, time: Date.now() })
  },
  // `increment` is just a resolver for the Mutation type
  Mutation: {
    increment: () => ({ count: ++count, time: Date.now() })
  },
  CountResult: {
    count: obj => obj.count,
    time: obj => obj.time
  }
};

const server = new ApolloServer({ typeDefs: schema, resolvers });
const handle = await server.listen();

const axios = require(axios);
// Call the `increment` mutation
await axios.post(handle.url, {
  query: mutation { increment { count, time } }
});

// After the `increment` mutation, `count` is now 1
const { data } = await axios.post(handle.url, {
  query: { getCount { count, time } }
});

data.data; // { getCount: { count: 1, time: 1581442587371 } }
© 版权声明
评论 抢沙发

请登录后发表评论