gql 和 buildSchema 有什么区别?

graphql-js buildSchemaapollo-server gql 有什么区别?他们的工作似乎非常相似。

iCMS 回答:gql 和 buildSchema 有什么区别?

首先要注意,apollo-server 的 gql 实际上是从 graphql-tag 重新导出的。 graphql-tag 是一个大约 150 行的软件包,它是默认的,几乎唯一有用的导出是 gql

背景简介:graphql-js 包在 Javascript 中提供了 GraphQL 的官方参考实现。它基本上提供了两个重要的东西:

  1. graphql 函数,它将处理针对 GraphQLSchema 对象的任何 GraphQL 查询(GraphQLSchema 对象是 graphql-js 表示您的解析架构的方式)。
  2. 一系列实用函数和类型,用于从字符串构建和验证 GraphQLSchema 函数使用的 graphql 对象。

现在,这是最终让我困惑的部分:在 graphql-js 中,将字符串转换为 GraphQLSchema 对象是一个两步过程: >

  • 第 1 步:字符串 -> AST(由 parse 函数完成)。
  • 第 2 步:AST -> GraphQLSchema(由 buildASTSchema 函数完成)。

这是因为 AST(抽象语法树)对许多其他甚至不一定了解 GraphQL 的工具很有用(例如参见 https://astexplorer.net/),而 GraphQLSchema 只是对 graphql-js 及相关软件有意义。

graphql-js 公开了执行这两个步骤的函数,这些函数被下游实现者(如 Apollo)重用。 buildSchema 只是将这两个步骤结合起来的便利包装器。它是literally this

/**
 * A helper function to build a GraphQLSchema directly from a source
 * document.
 */
export function buildSchema(source: string | Source): GraphQLSchema {
  return buildASTSchema(parse(source));
}

另一方面,gql 的输出只是 AST 部分,这与 graphql-js parse 函数的输出相同。由于上述原因,gql 不直接返回 GraphQLSchema:AST 很有用(注意 gql 也做了一些基本的事情,比如有状态缓存,并将合并一个架构字符串数组成一个单一的 AST 结果......)。不过最终 AST 必须转换为适当的模式,而 apollo-server 在服务器实例化时(大概)会这样做。

为了显示关系,我们可以将gql的输出(与parse相同)通过buildASTSchema运行它(就像buildSchema一样)然后将它传递给{ {1}} 和它的工作原理相同:

graphql

给予:

import { graphql,buildSchema,buildASTSchema } from 'graphql';
import { gql } from 'apollo-server'; // equivalent to 'import gql from graphql-tag'

const schemaString = `
  type Query {
    hello: String!
  }
`;

const a = buildASTSchema(gql(schemaString));
const b = buildSchema(schemaString);

graphql(a,'{ hello }',{ hello: () => 'Hello world!' }).then((response) => {
  console.log(response);
});
graphql(b,{ hello: () => 'Hello world!' }).then((response) => {
  console.log(response);
});
本文链接:https://www.f2er.com/455143.html

大家都在问