UNPKG

graphql-scalars

Version:

A collection of scalar types not included in base GraphQL.

57 lines (56 loc) 1.9 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.identity = identity; exports.ensureObject = ensureObject; exports.parseObject = parseObject; exports.parseLiteral = parseLiteral; const graphql_1 = require("graphql"); const error_js_1 = require("../../error.js"); function identity(value) { return value; } function ensureObject(value, ast) { if (typeof value !== 'object' || value === null || Array.isArray(value)) { throw (0, error_js_1.createGraphQLError)(`JSONObject cannot represent non-object value: ${value}`, ast ? { nodes: ast, } : undefined); } return value; } function parseObject(ast, variables) { if (ast.kind !== graphql_1.Kind.OBJECT) { throw (0, error_js_1.createGraphQLError)(`JSONObject cannot represent non-object value: ${(0, graphql_1.print)(ast)}`, ast ? { nodes: ast, } : undefined); } const value = Object.create(null); ast.fields.forEach(field => { // eslint-disable-next-line no-use-before-define value[field.name.value] = parseLiteral(field.value, variables); }); return value; } function parseLiteral(ast, variables) { switch (ast.kind) { case graphql_1.Kind.STRING: case graphql_1.Kind.BOOLEAN: return ast.value; case graphql_1.Kind.INT: case graphql_1.Kind.FLOAT: return parseFloat(ast.value); case graphql_1.Kind.OBJECT: return parseObject(ast, variables); case graphql_1.Kind.LIST: return ast.values.map(n => parseLiteral(n, variables)); case graphql_1.Kind.NULL: return null; case graphql_1.Kind.VARIABLE: { const name = ast.name.value; return variables ? variables[name] : undefined; } } }