GraphQL LogoGraphQL

graphql/language

graphql/language 模块负责解析和操作 GraphQL 语言。您可以从 graphql/language 模块或根 graphql 模块导入。例如

import { Source } from "graphql" // ES6
var { Source } = require("graphql") // CommonJS

概述#

源代码

词法分析器

解析器

访问者

打印机

源代码#

源代码#

export class Source {
constructor(body: string, name?: string)
}

GraphQL 的源输入表示。名称是可选的,但主要对将 GraphQL 文档存储在源文件中的客户端有用;例如,如果 GraphQL 输入位于 Foo.graphql 文件中,则名称可能为“Foo.graphql”。

getLocation#

function getLocation(source: Source, position: number): SourceLocation
type SourceLocation = {
line: number;
column: number;
}

获取 Source 和 UTF-8 字符偏移量,并返回相应的行和列作为 SourceLocation。

词法分析器#

lex#

function lex(source: Source): Lexer;
type Lexer = (resetPosition?: number) => Token;
export type Token = {
kind: number;
start: number;
end: number;
value: ?string;
};

给定一个 Source 对象,这将返回该源的词法分析器。词法分析器是一个函数,它就像一个生成器,每次调用它时,它都会返回 Source 中的下一个标记。假设源代码可以进行词法分析,词法分析器发出的最后一个标记将是 EOF 类型的,此后,无论何时调用词法分析器,它都会重复返回 EOF 标记。

词法分析器函数的参数是可选的,可用于将词法分析器回溯或快进到源代码中的新位置。

解析器#

解析#

export function parse(
source: Source | string,
options?: ParseOptions
): Document

给定一个 GraphQL 源代码,将其解析为一个文档。

如果遇到语法错误,则抛出 GraphQLError。

解析值#

export function parseValue(
source: Source | string,
options?: ParseOptions
): Value

给定包含 GraphQL 值的字符串,解析该值的 AST。

如果遇到语法错误,则抛出 GraphQLError。

这在直接操作 GraphQL 值并独立于完整 GraphQL 文档的工具中很有用。

种类#

一个枚举,描述了不同类型的 AST 节点。

访问者#

访问#

function visit(root, visitor, keyMap)

visit() 将使用深度优先遍历遍历 AST,在遍历中的每个节点调用访问者的 enter 函数,并在访问该节点及其所有子节点后调用 leave 函数。

通过从 enter 和 leave 函数返回不同的值,可以改变访问者的行为,包括跳过 AST 的子树(通过返回 false),通过返回一个值或 null 来编辑 AST 以删除该值,或者通过返回 BREAK 来停止整个遍历。

当使用 visit() 编辑 AST 时,原始 AST 不会被修改,并且将从 visit 函数返回一个应用了更改的 AST 的新版本。

var editedAST = visit(ast, {
enter(node, key, parent, path, ancestors) {
// @return
// undefined: no action
// false: skip visiting this node
// visitor.BREAK: stop visiting altogether
// null: delete this node
// any value: replace this node with the returned value
},
leave(node, key, parent, path, ancestors) {
// @return
// undefined: no action
// false: no action
// visitor.BREAK: stop visiting altogether
// null: delete this node
// any value: replace this node with the returned value
},
})

除了提供 enter() 和 leave() 函数之外,访问者还可以提供与 AST 节点类型相同的名称的函数,或者在命名键处提供 enter/leave 访问者,从而导致访问者 API 的四种排列

  1. 在进入特定类型的节点时触发的命名访问者。
visit(ast, {
Kind(node) {
// enter the "Kind" node
},
})
  1. 在进入和离开特定类型的节点时触发的命名访问者。
visit(ast, {
Kind: {
enter(node) {
// enter the "Kind" node
}
leave(node) {
// leave the "Kind" node
}
}
})
  1. 在进入和离开任何节点时触发的通用访问者。
visit(ast, {
enter(node) {
// enter any node
},
leave(node) {
// leave any node
},
})
  1. 用于进入和离开特定类型节点的并行访问者。
visit(ast, {
enter: {
Kind(node) {
// enter the "Kind" node
},
},
leave: {
Kind(node) {
// leave the "Kind" node
},
},
})

BREAK#

visitor 文档中描述的哨兵 BREAK 值。

打印机#

打印#

function print(ast): string

使用一组合理的格式规则将 AST 转换为字符串。

继续阅读 →graphql/type