-
Notifications
You must be signed in to change notification settings - Fork 61
/
index.js
81 lines (71 loc) · 2.47 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import { GraphQLScalarType } from 'graphql';
import { Kind, print } from 'graphql/language';
function identity(value) {
return value;
}
function ensureObject(value) {
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
throw new TypeError(
`JSONObject cannot represent non-object value: ${value}`,
);
}
return value;
}
function parseObject(typeName, ast, variables) {
const value = Object.create(null);
ast.fields.forEach((field) => {
// eslint-disable-next-line no-use-before-define
value[field.name.value] = parseLiteral(typeName, field.value, variables);
});
return value;
}
function parseLiteral(typeName, ast, variables) {
switch (ast.kind) {
case Kind.STRING:
case Kind.BOOLEAN:
return ast.value;
case Kind.INT:
case Kind.FLOAT:
return parseFloat(ast.value);
case Kind.OBJECT:
return parseObject(typeName, ast, variables);
case Kind.LIST:
return ast.values.map((n) => parseLiteral(typeName, n, variables));
case Kind.NULL:
return null;
case Kind.VARIABLE:
return variables ? variables[ast.name.value] : undefined;
default:
throw new TypeError(`${typeName} cannot represent value: ${print(ast)}`);
}
}
// This named export is intended for users of CommonJS. Users of ES modules
// should instead use the default export.
export const GraphQLJSON = new GraphQLScalarType({
name: 'JSON',
description:
'The `JSON` scalar type represents JSON values as specified by [ECMA-404](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf).',
specifiedByUrl:
'http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf',
serialize: identity,
parseValue: identity,
parseLiteral: (ast, variables) => parseLiteral('JSON', ast, variables),
});
export default GraphQLJSON;
export const GraphQLJSONObject = new GraphQLScalarType({
name: 'JSONObject',
description:
'The `JSONObject` scalar type represents JSON objects as specified by [ECMA-404](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf).',
specifiedByUrl:
'http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf',
serialize: ensureObject,
parseValue: ensureObject,
parseLiteral: (ast, variables) => {
if (ast.kind !== Kind.OBJECT) {
throw new TypeError(
`JSONObject cannot represent non-object value: ${print(ast)}`,
);
}
return parseObject('JSONObject', ast, variables);
},
});