UNPKG

2.86 kBJavaScriptView Raw
1import { getResponseKeyFromInfo, getRootTypeMap } from '@graphql-tools/utils';
2import { delegateToSchema, getSubschema, resolveExternalValue, isExternalObject, getUnpathedErrors, } from '@graphql-tools/delegate';
3export function generateProxyingResolvers(subschemaConfig) {
4 var _a;
5 const targetSchema = subschemaConfig.schema;
6 const createProxyingResolver = (_a = subschemaConfig.createProxyingResolver) !== null && _a !== void 0 ? _a : defaultCreateProxyingResolver;
7 const rootTypeMap = getRootTypeMap(targetSchema);
8 const resolvers = {};
9 for (const [operation, rootType] of rootTypeMap.entries()) {
10 const typeName = rootType.name;
11 const fields = rootType.getFields();
12 resolvers[typeName] = {};
13 for (const fieldName in fields) {
14 const proxyingResolver = createProxyingResolver({
15 subschemaConfig,
16 operation,
17 fieldName,
18 });
19 const finalResolver = createPossiblyNestedProxyingResolver(subschemaConfig, proxyingResolver);
20 if (operation === 'subscription') {
21 resolvers[typeName][fieldName] = {
22 subscribe: finalResolver,
23 resolve: identical,
24 };
25 }
26 else {
27 resolvers[typeName][fieldName] = {
28 resolve: finalResolver,
29 };
30 }
31 }
32 }
33 return resolvers;
34}
35function identical(value) {
36 return value;
37}
38function createPossiblyNestedProxyingResolver(subschemaConfig, proxyingResolver) {
39 return function possiblyNestedProxyingResolver(parent, args, context, info) {
40 if (parent != null) {
41 const responseKey = getResponseKeyFromInfo(info);
42 // Check to see if the parent contains a proxied result
43 if (isExternalObject(parent)) {
44 const unpathedErrors = getUnpathedErrors(parent);
45 const subschema = getSubschema(parent, responseKey);
46 // If there is a proxied result from this subschema, return it
47 // This can happen even for a root field when the root type ia
48 // also nested as a field within a different type.
49 if (subschemaConfig === subschema && parent[responseKey] !== undefined) {
50 return resolveExternalValue(parent[responseKey], unpathedErrors, subschema, context, info);
51 }
52 }
53 }
54 return proxyingResolver(parent, args, context, info);
55 };
56}
57export function defaultCreateProxyingResolver({ subschemaConfig, operation, }) {
58 return function proxyingResolver(_parent, _args, context, info) {
59 return delegateToSchema({
60 schema: subschemaConfig,
61 operation,
62 context,
63 info,
64 });
65 };
66}