UNPKG

1.9 kBJavaScriptView Raw
1import { getNullableType, isInputObjectType, isLeafType, isListType, } from 'graphql';
2import { asArray } from './helpers.js';
3export function transformInputValue(type, value, inputLeafValueTransformer = null, inputObjectValueTransformer = null) {
4 if (value == null) {
5 return value;
6 }
7 const nullableType = getNullableType(type);
8 if (isLeafType(nullableType)) {
9 return inputLeafValueTransformer != null
10 ? inputLeafValueTransformer(nullableType, value)
11 : value;
12 }
13 else if (isListType(nullableType)) {
14 return asArray(value).map((listMember) => transformInputValue(nullableType.ofType, listMember, inputLeafValueTransformer, inputObjectValueTransformer));
15 }
16 else if (isInputObjectType(nullableType)) {
17 const fields = nullableType.getFields();
18 const newValue = {};
19 for (const key in value) {
20 const field = fields[key];
21 if (field != null) {
22 newValue[key] = transformInputValue(field.type, value[key], inputLeafValueTransformer, inputObjectValueTransformer);
23 }
24 }
25 return inputObjectValueTransformer != null
26 ? inputObjectValueTransformer(nullableType, newValue)
27 : newValue;
28 }
29 // unreachable, no other possible return value
30}
31export function serializeInputValue(type, value) {
32 return transformInputValue(type, value, (t, v) => {
33 try {
34 return t.serialize(v);
35 }
36 catch {
37 return v;
38 }
39 });
40}
41export function parseInputValue(type, value) {
42 return transformInputValue(type, value, (t, v) => {
43 try {
44 return t.parseValue(v);
45 }
46 catch {
47 return v;
48 }
49 });
50}
51export function parseInputValueLiteral(type, value) {
52 return transformInputValue(type, value, (t, v) => t.parseLiteral(v, {}));
53}