UNPKG

@cran/gql.core

Version:

Cran/GraphQL Core Utilities

35 lines (34 loc) 1.18 kB
import { Kind } from "graphql/language/kinds"; import { isNode } from "graphql/language/ast"; import { print } from "graphql/language/printer"; export function parseError(type, ast, reason = "input syntax") { throw new TypeError(`invalid ${reason} for type ${type}: ${isNode(ast) ? print(ast) : ast}`); } export function parseObject(type, ast, variables) { const value = Object.create(null); for (const field of ast.fields) { value[field.name.value] = parseLiteral(type, field.value, variables); } return value; } export function parseLiteral(type, ast, variables) { switch (ast.kind) { case Kind.STRING: case Kind.BOOLEAN: case Kind.INT: case Kind.FLOAT: return ast.value; case Kind.OBJECT: return parseObject(type, ast, variables); case Kind.LIST: return ast.values.map(function mapValue(value) { return parseLiteral(type, value, variables); }); case Kind.NULL: return null; case Kind.VARIABLE: return variables?.[ast.name.value]; default: parseError(type, ast); } }