-
-
Notifications
You must be signed in to change notification settings - Fork 827
Expand file tree
/
Copy pathbatchDelegateToSchema.ts
More file actions
89 lines (73 loc) · 2.2 KB
/
batchDelegateToSchema.ts
File metadata and controls
89 lines (73 loc) · 2.2 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { BatchDelegateOptions } from './types';
import { AsyncExecutionResult, ExecutionResult, getNullableType, GraphQLList } from 'graphql';
import {
DelegationContext,
createRequestFromInfo,
externalValueFromResult,
getDelegationContext,
getDelegatingOperation,
Receiver,
} from '@graphql-tools/delegate';
import { isAsyncIterable, relocatedError } from '@graphql-tools/utils';
import { getLoader } from './getLoader';
export async function batchDelegateToSchema(options: BatchDelegateOptions): Promise<any> {
const key = options.key;
if (key == null) {
return null;
} else if (Array.isArray(key) && !key.length) {
return [];
}
const {
info,
operationName,
operation = getDelegatingOperation(info.parentType, info.schema),
fieldName = info.fieldName,
returnType = info.returnType,
selectionSet,
fieldNodes,
} = options;
if (operation !== 'query' && operation !== 'mutation') {
throw new Error(`Batch delegation not possible for operation '${operation}'.`);
}
const request = createRequestFromInfo({
info,
operation,
fieldName,
selectionSet,
fieldNodes,
operationName,
});
const delegationContext = getDelegationContext({
request,
onLocatedError: originalError => relocatedError(originalError, originalError.path.slice(1)),
...options,
operation,
fieldName,
returnType,
});
const loader = getLoader(options, request, delegationContext);
if (Array.isArray(key)) {
const results = await loader.loadMany(key);
return results.map(result =>
onResult(result, {
...delegationContext,
returnType: (getNullableType(delegationContext.returnType) as GraphQLList<any>).ofType,
})
);
}
const result = await loader.load(key);
return onResult(result, delegationContext);
}
function onResult(
result: Error | ExecutionResult | AsyncIterableIterator<AsyncExecutionResult>,
delegationContext: DelegationContext
): any {
if (result instanceof Error) {
return result;
}
if (isAsyncIterable(result)) {
const receiver = new Receiver(result, delegationContext);
return receiver.getInitialValue();
}
return externalValueFromResult(result, delegationContext);
}