-
Notifications
You must be signed in to change notification settings - Fork 33
/
transport-input.ts
46 lines (38 loc) · 1.43 KB
/
transport-input.ts
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
import {
GraphQLEnumType,
GraphQLInputType,
GraphQLScalarType,
getNullableType,
isLeafType,
isListType,
isInputObjectType,
} from 'graphql';
type InputValueTransformer = (type: GraphQLEnumType | GraphQLScalarType, originalValue: any) => any;
export function transformInputValue(type: GraphQLInputType, value: any, transformer: InputValueTransformer) {
if (value == null) {
return value;
}
const nullableType = getNullableType(type);
if (isLeafType(nullableType)) {
return transformer(nullableType, value);
} else if (isListType(nullableType)) {
return value.map((listMember: any) => transformInputValue(nullableType.ofType, listMember, transformer));
} else if (isInputObjectType(nullableType)) {
const fields = nullableType.getFields();
const newValue = {};
Object.keys(value).forEach((key) => {
newValue[key] = transformInputValue(fields[key].type, value[key], transformer);
});
return newValue;
}
// unreachable, no other possible return value
}
export function serializeInputValue(type: GraphQLInputType, value: any) {
return transformInputValue(type, value, (t, v) => t.serialize(v));
}
export function parseInputValue(type: GraphQLInputType, value: any) {
return transformInputValue(type, value, (t, v) => t.parseValue(v));
}
export function parseInputValueLiteral(type: GraphQLInputType, value: any) {
return transformInputValue(type, value, (t, v) => t.parseLiteral(v, {}));
}