UNPKG

3.09 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.astFromValueUntyped = void 0;
4const graphql_1 = require("graphql");
5/**
6 * Produces a GraphQL Value AST given a JavaScript object.
7 * Function will match JavaScript/JSON values to GraphQL AST schema format
8 * by using the following mapping.
9 *
10 * | JSON Value | GraphQL Value |
11 * | ------------- | -------------------- |
12 * | Object | Input Object |
13 * | Array | List |
14 * | Boolean | Boolean |
15 * | String | String |
16 * | Number | Int / Float |
17 * | BigInt | Int |
18 * | null | NullValue |
19 *
20 */
21function astFromValueUntyped(value) {
22 // only explicit null, not undefined, NaN
23 if (value === null) {
24 return { kind: graphql_1.Kind.NULL };
25 }
26 // undefined
27 if (value === undefined) {
28 return null;
29 }
30 // Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but
31 // the value is not an array, convert the value using the list's item type.
32 if (Array.isArray(value)) {
33 const valuesNodes = [];
34 for (const item of value) {
35 const itemNode = astFromValueUntyped(item);
36 if (itemNode != null) {
37 valuesNodes.push(itemNode);
38 }
39 }
40 return { kind: graphql_1.Kind.LIST, values: valuesNodes };
41 }
42 if (typeof value === 'object') {
43 if (value?.toJSON) {
44 return astFromValueUntyped(value.toJSON());
45 }
46 const fieldNodes = [];
47 for (const fieldName in value) {
48 const fieldValue = value[fieldName];
49 const ast = astFromValueUntyped(fieldValue);
50 if (ast) {
51 fieldNodes.push({
52 kind: graphql_1.Kind.OBJECT_FIELD,
53 name: { kind: graphql_1.Kind.NAME, value: fieldName },
54 value: ast,
55 });
56 }
57 }
58 return { kind: graphql_1.Kind.OBJECT, fields: fieldNodes };
59 }
60 // Others serialize based on their corresponding JavaScript scalar types.
61 if (typeof value === 'boolean') {
62 return { kind: graphql_1.Kind.BOOLEAN, value };
63 }
64 if (typeof value === 'bigint') {
65 return { kind: graphql_1.Kind.INT, value: String(value) };
66 }
67 // JavaScript numbers can be Int or Float values.
68 if (typeof value === 'number' && isFinite(value)) {
69 const stringNum = String(value);
70 return integerStringRegExp.test(stringNum)
71 ? { kind: graphql_1.Kind.INT, value: stringNum }
72 : { kind: graphql_1.Kind.FLOAT, value: stringNum };
73 }
74 if (typeof value === 'string') {
75 return { kind: graphql_1.Kind.STRING, value };
76 }
77 throw new TypeError(`Cannot convert value to AST: ${value}.`);
78}
79exports.astFromValueUntyped = astFromValueUntyped;
80/**
81 * IntValue:
82 * - NegativeSign? 0
83 * - NegativeSign? NonZeroDigit ( Digit+ )?
84 */
85const integerStringRegExp = /^-?(?:0|[1-9][0-9]*)$/;