Features
- Typed GraphQL AST as per October 2021 specification
- Error resilience
- lexing and parsing does not fail or
panic
if a lexical or a syntax error is found
- lexing and parsing does not fail or
- GraphQL lexer
- GraphQL parser
Getting started
Add this to your Cargo.toml
to start using apollo-parser
:
# Just an example, change to the necessary package version.
[]
= "0.2.5"
Or using cargo-edit:
Usage
apollo-parser
is built to parse both GraphQL schemas and queries according to
the latest October 2021 specification. It produces a typed syntax tree that
then can be walked, extracting all the necessary information. You can quick
start with:
use Parser;
let input = "union SearchResult = Photo | Person | Cat | Dog";
let parser = new;
let ast = parser.parse;
apollo-parser
is built to be error-resilient. This means we don't abort parsing (or lexing) if an error occurs. That means parser.parse()
will always produce an AST, and it will be accompanied by any errors that are encountered:
use Parser;
let input = "union SearchResult = Photo | Person | Cat | Dog";
let parser = new;
let ast = parser.parse;
// ast.errors() returns an iterator with the errors encountered during lexing and parsing
assert_eq!;
// ast.document() gets the Document, or root node, of the tree that you can
// start iterating on.
let doc = ast.document;
Examples
Two examples outlined here:
The examples directory in this repository has a few more useful implementations such as:
- using apollo-rs with miette to display error diagnostics
- using apollo-rs with annotate_snippets to display error diagnostics
- checking for unused variables
Get field names in an object
use ;
let input = "
type ProductDimension {
size: String
weight: Float @tag(name: \"hi from inventory value type field\")
}
";
let parser = new;
let ast = parser.parse;
assert_eq!;
let doc = ast.document;
for def in doc.definitions
Get variables used in a query
use ;
let input = "
query GraphQuery($graph_id: ID!, $variant: String) {
service(id: $graph_id) {
schema(tag: $variant) {
document
}
}
}
";
let parser = new;
let ast = parser.parse;
assert_eq!;
let doc = ast.document;
for def in doc.definitions
License
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or https://opensource.org/licenses/MIT)
at your option.