UNPKG

3.08 kBJavaScriptView Raw
1import { GraphQLScalarType, isScalarType, isEnumType, isInterfaceType, isUnionType, isObjectType, isSpecifiedScalarType, } from 'graphql';
2export function getResolversFromSchema(schema,
3// Include default merged resolvers
4includeDefaultMergedResolver) {
5 var _a, _b;
6 const resolvers = Object.create(null);
7 const typeMap = schema.getTypeMap();
8 for (const typeName in typeMap) {
9 if (!typeName.startsWith('__')) {
10 const type = typeMap[typeName];
11 if (isScalarType(type)) {
12 if (!isSpecifiedScalarType(type)) {
13 const config = type.toConfig();
14 delete config.astNode; // avoid AST duplication elsewhere
15 resolvers[typeName] = new GraphQLScalarType(config);
16 }
17 }
18 else if (isEnumType(type)) {
19 resolvers[typeName] = {};
20 const values = type.getValues();
21 for (const value of values) {
22 resolvers[typeName][value.name] = value.value;
23 }
24 }
25 else if (isInterfaceType(type)) {
26 if (type.resolveType != null) {
27 resolvers[typeName] = {
28 __resolveType: type.resolveType,
29 };
30 }
31 }
32 else if (isUnionType(type)) {
33 if (type.resolveType != null) {
34 resolvers[typeName] = {
35 __resolveType: type.resolveType,
36 };
37 }
38 }
39 else if (isObjectType(type)) {
40 resolvers[typeName] = {};
41 if (type.isTypeOf != null) {
42 resolvers[typeName].__isTypeOf = type.isTypeOf;
43 }
44 const fields = type.getFields();
45 for (const fieldName in fields) {
46 const field = fields[fieldName];
47 if (field.subscribe != null) {
48 resolvers[typeName][fieldName] = resolvers[typeName][fieldName] || {};
49 resolvers[typeName][fieldName].subscribe = field.subscribe;
50 }
51 if (field.resolve != null && ((_a = field.resolve) === null || _a === void 0 ? void 0 : _a.name) !== 'defaultFieldResolver') {
52 switch ((_b = field.resolve) === null || _b === void 0 ? void 0 : _b.name) {
53 case 'defaultMergedResolver':
54 if (!includeDefaultMergedResolver) {
55 continue;
56 }
57 break;
58 case 'defaultFieldResolver':
59 continue;
60 }
61 resolvers[typeName][fieldName] = resolvers[typeName][fieldName] || {};
62 resolvers[typeName][fieldName].resolve = field.resolve;
63 }
64 }
65 }
66 }
67 }
68 return resolvers;
69}