Parsing GraphQL
Lanexio Parser parses both GraphQL executable documents and SDL (Schema Definition Language) with automatic detection. A single function handles both modes.
Quick start
Section titled “Quick start”-
Install the package.
Terminal window pnpm add @lanexio/parser-grammar-graphqlTerminal window npm install @lanexio/parser-grammar-graphqlTerminal window yarn add @lanexio/parser-grammar-graphql -
Parse a query.
import { parseGraphql } from '@lanexio/parser-grammar-graphql';const encoder = new TextEncoder();const tree = parseGraphql(encoder.encode(`query getUser($id: ID!) {user(id: $id) {nameemail}}`)); -
Parse a schema.
import { parseGraphql } from '@lanexio/parser-grammar-graphql';const tree = parseGraphql(encoder.encode(`type User {id: ID!name: String!email: String}`));
Auto-detection
Section titled “Auto-detection”The parser inspects the input and routes to the executable-document parser or the SDL parser automatically. You do not need to specify which mode to use. Input starting with {, query, mutation, subscription, or fragment is treated as an executable document. Input starting with type, interface, enum, union, input, schema, scalar, directive, or extend is treated as SDL.
Inspecting the tree
Section titled “Inspecting the tree”Each top-level definition is a node in the tree. Operations, fragments, fields, arguments, types, and directives are all represented with GraphqlKind constants. The tree is a zero-copy flat AST — traverse it with a cursor.
const cursor = tree.cursor();cursor.gotoFirstChild(); // first operation or definition
while (cursor.gotoNextSibling()) { console.log(cursor.current.kind);}