/
extensions.ts
59 lines (49 loc) · 2 KB
/
extensions.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
47
48
49
50
51
52
53
54
55
56
57
58
59
import { GraphQLSchema, GraphQLObjectType, GraphQLEnumType } from 'graphql';
import { ExtensionsObject, Maybe, mergeDeep, SchemaExtensions } from '@graphql-tools/utils';
export { extractExtensionsFromSchema } from '@graphql-tools/utils';
export function mergeExtensions(extensions: SchemaExtensions[]): SchemaExtensions {
return mergeDeep(extensions);
}
function applyExtensionObject(
obj: Maybe<{ extensions: Maybe<Readonly<Record<string, any>>> }>,
extensions: ExtensionsObject
) {
if (!obj) {
return;
}
obj.extensions = mergeDeep([obj.extensions || {}, extensions || {}]);
}
export function applyExtensions(schema: GraphQLSchema, extensions: SchemaExtensions): GraphQLSchema {
applyExtensionObject(schema, extensions.schemaExtensions);
for (const [typeName, data] of Object.entries(extensions.types || {})) {
const type = schema.getType(typeName);
if (type) {
applyExtensionObject(type, data.extensions);
if (data.type === 'object' || data.type === 'interface') {
for (const [fieldName, fieldData] of Object.entries(data.fields)) {
const field = (type as GraphQLObjectType).getFields()[fieldName];
if (field) {
applyExtensionObject(field, fieldData.extensions);
for (const [arg, argData] of Object.entries(fieldData.arguments)) {
applyExtensionObject(
field.args.find(a => a.name === arg),
argData
);
}
}
}
} else if (data.type === 'input') {
for (const [fieldName, fieldData] of Object.entries(data.fields)) {
const field = (type as GraphQLObjectType).getFields()[fieldName];
applyExtensionObject(field, fieldData.extensions);
}
} else if (data.type === 'enum') {
for (const [valueName, valueData] of Object.entries(data.values)) {
const value = (type as GraphQLEnumType).getValue(valueName);
applyExtensionObject(value, valueData);
}
}
}
}
return schema;
}