graphql/language
模組負責剖析和操作 GraphQL 語言。您可以從 graphql/language
模組或根目錄 graphql
模組匯入。例如
import { Source } from "graphql" // ES6var { Source } = require("graphql") // CommonJS
來源
詞法分析器
剖析器
訪客
印表機
export class Source { constructor(body: string, name?: string)}
GraphQL 來源輸入的表示形式。名稱是選填的,但對將 GraphQL 文件儲存在來源檔案中的客戶端來說非常有用;例如,如果 GraphQL 輸入位於 Foo.graphql 檔案中,則名稱為「Foo.graphql」會很有用。
function getLocation(source: Source, position: number): SourceLocation
type SourceLocation = { line: number; column: number;}
取得 Source 和 UTF-8 字元偏移量,並傳回對應的列和欄位,作為 SourceLocation。
function lex(source: Source): Lexer;
type Lexer = (resetPosition?: number) => Token;
export type Token = { kind: number; start: number; end: number; value: ?string;};
針對 Source 物件,傳回該來源的 Lexer。Lexer 是一個函式,其作用類似於產生器,每次呼叫時,它會傳回 Source 中的下一個 token。假設來源會進行詞法分析,則由詞法分析器發出的最後一個 Token 會是 EOF 類型的,之後詞法分析器會在每次呼叫時重複傳回 EOF token。
詞法分析器函式的引數是選用的,可用於將詞法分析器倒轉或快轉到來源中的新位置。
export function parse( source: Source | string, options?: ParseOptions): Document
針對 GraphQL 來源,將其解析成 Document。
如果遇到語法錯誤,則擲回 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 節點種類相同名稱的函式,或在命名金鑰中輸入/離開訪客,導致訪客 API 有四種排列組合
visit(ast, { Kind(node) { // enter the "Kind" node },})
visit(ast, { Kind: { enter(node) { // enter the "Kind" node } leave(node) { // leave the "Kind" node } }})
visit(ast, { enter(node) { // enter any node }, leave(node) { // leave any node },})
visit(ast, { enter: { Kind(node) { // enter the "Kind" node }, }, leave: { Kind(node) { // leave the "Kind" node }, },})
visitor
文件中所述的哨兵 BREAK
值。
function print(ast): string
使用一套合理的格式化規則將 AST 轉換成字串。