Skip to content

Parsing GraphQL

Lanexio Parser parses both GraphQL executable documents and SDL (Schema Definition Language) with automatic detection. A single function handles both modes.

  1. Install the package.

    Terminal window
    pnpm add @lanexio/parser-grammar-graphql
  2. 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) {
    name
    email
    }
    }
    `));
  3. Parse a schema.

    import { parseGraphql } from '@lanexio/parser-grammar-graphql';
    const tree = parseGraphql(encoder.encode(`
    type User {
    id: ID!
    name: String!
    email: String
    }
    `));

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.

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);
}