Skip to content

Commit 1dc6b4d

Browse files
committed
proof of concept
1 parent e42444e commit 1dc6b4d

File tree

5 files changed

+129
-30
lines changed

5 files changed

+129
-30
lines changed

packages/delegate/src/defaultMergedResolver.ts

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { defaultFieldResolver, GraphQLResolveInfo } from 'graphql';
22

3-
import { getResponseKeyFromInfo } from '@graphql-tools/utils';
3+
import { getResponseKeyFromInfo, ExecutionResult } from '@graphql-tools/utils';
44

55
import { resolveExternalValue } from './resolveExternalValue';
66
import { getSubschema } from './Subschema';
@@ -18,7 +18,7 @@ export function defaultMergedResolver(
1818
args: Record<string, any>,
1919
context: Record<string, any>,
2020
info: GraphQLResolveInfo
21-
) {
21+
): any {
2222
if (!parent) {
2323
return null;
2424
}
@@ -34,16 +34,26 @@ export function defaultMergedResolver(
3434
const data = parent[responseKey];
3535
const unpathedErrors = getUnpathedErrors(parent);
3636

37-
// To Do: extract this section to separate function.
38-
// If proxied result with defer or stream, result may be initially undefined
39-
// so must call out to a to-be-created Receiver abstraction
40-
// (as opposed to Dispatcher within graphql-js) that will notify of data arrival
41-
42-
if (data === undefined) {
43-
return 'test';
37+
// To Do:
38+
// add support for transforms
39+
// call out to Receiver abstraction that will publish all patches with channel based on path
40+
// edit code below to subscribe to appropriate channel based on path
41+
// so as to handle multiple defer patches and discriminate between them without need for labels
42+
43+
if (data === undefined && 'ASYNC_ITERABLE' in parent) {
44+
const asyncIterable = parent['ASYNC_ITERABLE'];
45+
return asyncIterableToResult(asyncIterable).then(patch => {
46+
return defaultMergedResolver(patch.data, args, context, info);
47+
});
4448
}
4549

4650
const subschema = getSubschema(parent, responseKey);
4751

4852
return resolveExternalValue(data, unpathedErrors, subschema, context, info);
4953
}
54+
55+
async function asyncIterableToResult(asyncIterable: AsyncIterable<ExecutionResult>): Promise<any> {
56+
const asyncIterator = asyncIterable[Symbol.asyncIterator]();
57+
const payload = await asyncIterator.next();
58+
return payload.value;
59+
}

packages/delegate/src/delegateToSchema.ts

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import {
22
subscribe,
3-
execute,
43
validate,
54
GraphQLSchema,
65
isSchema,
@@ -13,9 +12,11 @@ import {
1312
GraphQLObjectType,
1413
} from 'graphql';
1514

15+
import { execute } from 'graphql/experimental';
16+
1617
import isPromise from 'is-promise';
1718

18-
import { mapAsyncIterator, ExecutionResult } from '@graphql-tools/utils';
19+
import { mapAsyncIterator, ExecutionResult, isAsyncIterable } from '@graphql-tools/utils';
1920

2021
import {
2122
IDelegateToSchemaOptions,
@@ -25,6 +26,7 @@ import {
2526
StitchingInfo,
2627
Endpoint,
2728
Transform,
29+
Executor,
2830
} from './types';
2931

3032
import { isSubschemaConfig } from './Subschema';
@@ -187,8 +189,16 @@ export function delegateRequest({
187189
info,
188190
});
189191

190-
if (isPromise(executionResult)) {
191-
return executionResult.then(originalResult => transformer.transformResult(originalResult));
192+
if (isAsyncIterable(executionResult)) {
193+
return asyncIterableToResult(executionResult).then(originalResult => {
194+
const transformedResult = transformer.transformResult(originalResult);
195+
transformedResult['ASYNC_ITERABLE'] = executionResult;
196+
return transformedResult;
197+
});
198+
} else if (isPromise(executionResult)) {
199+
return (executionResult as Promise<ExecutionResult>).then(originalResult =>
200+
transformer.transformResult(originalResult)
201+
);
192202
}
193203
return transformer.transformResult(executionResult);
194204
}
@@ -201,7 +211,7 @@ export function delegateRequest({
201211
context,
202212
info,
203213
}).then((subscriptionResult: AsyncIterableIterator<ExecutionResult> | ExecutionResult) => {
204-
if (Symbol.asyncIterator in subscriptionResult) {
214+
if (isAsyncIterable(subscriptionResult)) {
205215
// "subscribe" to the subscription result and map the result through the transforms
206216
return mapAsyncIterator<ExecutionResult, any>(
207217
subscriptionResult as AsyncIterableIterator<ExecutionResult>,
@@ -227,15 +237,15 @@ function validateRequest(targetSchema: GraphQLSchema, document: DocumentNode) {
227237
}
228238
}
229239

230-
function createDefaultExecutor(schema: GraphQLSchema, rootValue: Record<string, any>) {
231-
return ({ document, context, variables, info }: ExecutionParams) =>
240+
function createDefaultExecutor(schema: GraphQLSchema, rootValue: Record<string, any>): Executor {
241+
return (({ document, context, variables, info }: ExecutionParams) =>
232242
execute({
233243
schema,
234244
document,
235245
contextValue: context,
236246
variableValues: variables,
237247
rootValue: rootValue ?? info?.rootValue,
238-
});
248+
})) as Executor;
239249
}
240250

241251
function createDefaultSubscriber(schema: GraphQLSchema, rootValue: Record<string, any>) {
@@ -248,3 +258,9 @@ function createDefaultSubscriber(schema: GraphQLSchema, rootValue: Record<string
248258
rootValue: rootValue ?? info?.rootValue,
249259
}) as any;
250260
}
261+
262+
async function asyncIterableToResult(asyncIterable: AsyncIterable<ExecutionResult>): Promise<any> {
263+
const asyncIterator = asyncIterable[Symbol.asyncIterator]();
264+
const payload = await asyncIterator.next();
265+
return payload.value;
266+
}

packages/delegate/src/getBatchingExecutor.ts

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,17 @@ import isPromise from 'is-promise';
44

55
import DataLoader from 'dataloader';
66

7-
import { ExecutionResult } from '@graphql-tools/utils';
7+
import { ExecutionResult, isAsyncIterable } from '@graphql-tools/utils';
88

9-
import { ExecutionParams, Endpoint } from './types';
9+
import { ExecutionParams, Endpoint, Executor } from './types';
1010
import { memoize2of3 } from './memoize';
1111
import { mergeExecutionParams } from './mergeExecutionParams';
1212
import { splitResult } from './splitResult';
1313

1414
export const getBatchingExecutor = memoize2of3(function (
1515
_context: Record<string, any>,
1616
endpoint: Endpoint,
17-
executor: ({ document, context, variables, info }: ExecutionParams) => ExecutionResult | Promise<ExecutionResult>
17+
executor: Executor
1818
) {
1919
const loader = new DataLoader(
2020
createLoadFn(
@@ -27,7 +27,7 @@ export const getBatchingExecutor = memoize2of3(function (
2727
});
2828

2929
function createLoadFn(
30-
executor: ({ document, context, variables, info }: ExecutionParams) => ExecutionResult | Promise<ExecutionResult>,
30+
executor: Executor,
3131
extensionsReducer: (mergedExtensions: Record<string, any>, executionParams: ExecutionParams) => Record<string, any>
3232
) {
3333
return async (execs: Array<ExecutionParams>): Promise<Array<ExecutionResult>> => {
@@ -53,10 +53,16 @@ function createLoadFn(
5353
const mergedExecutionParams = mergeExecutionParams(execBatch, extensionsReducer);
5454
const executionResult = executor(mergedExecutionParams);
5555

56-
if (isPromise(executionResult)) {
56+
if (isAsyncIterable(executionResult)) {
57+
throw new Error('batching not yet possible with queries that return an async iterable (defer/stream)');
58+
// requires splitting up the async iterable into multiple async iterables by path versus possibly just promises
59+
// so requires analyzing which of the results would get an async iterable (ie included defer/stream within the subdocument)
60+
// or returning an async iterable even though defer/stream was not actually present, which is probably simpler
61+
// but most probably against the spec.
62+
} else if (isPromise(executionResult)) {
5763
containsPromises = true;
5864
}
59-
executionResults.push(executionResult);
65+
executionResults.push(executionResult as ExecutionResult);
6066
});
6167

6268
if (containsPromises) {

packages/delegate/src/types.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ import {
1414
GraphQLError,
1515
} from 'graphql';
1616

17+
import { AsyncExecutionResult } from 'graphql/experimental';
18+
1719
import DataLoader from 'dataloader';
1820

1921
import { Operation, Request, TypeMap, ExecutionResult } from '@graphql-tools/utils';
@@ -131,7 +133,9 @@ export type AsyncExecutor = <
131133
export type SyncExecutor = <TReturn = Record<string, any>, TArgs = Record<string, any>, TContext = Record<string, any>>(
132134
params: ExecutionParams<TArgs, TContext>
133135
) => ExecutionResult<TReturn>;
134-
export type Executor = AsyncExecutor | SyncExecutor;
136+
export type Executor = <TReturn = Record<string, any>, TArgs = Record<string, any>, TContext = Record<string, any>>(
137+
params: ExecutionParams<TArgs, TContext>
138+
) => Promise<ExecutionResult<TReturn>> | ExecutionResult<TReturn> | AsyncIterable<AsyncExecutionResult>;
135139
export type Subscriber = <TReturn = Record<string, any>, TArgs = Record<string, any>, TContext = Record<string, any>>(
136140
params: ExecutionParams<TArgs, TContext>
137141
) => Promise<AsyncIterator<ExecutionResult<TReturn>> | ExecutionResult<TReturn>>;

packages/delegate/tests/deferStream.test.ts

Lines changed: 69 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,41 @@
11
import { graphql } from 'graphql/experimental';
22

33
import { makeExecutableSchema } from '@graphql-tools/schema';
4+
import { stitchSchemas } from '@graphql-tools/stitch';
5+
import { isAsyncIterable } from '@graphql-tools/utils';
46

57
describe('defer support', () => {
6-
test('should work', async () => {
8+
test('should work for root fields', async () => {
79
const schema = makeExecutableSchema({
810
typeDefs: `
911
type Query {
10-
test(input: String): String
12+
test: String
1113
}
1214
`,
1315
resolvers: {
1416
Query: {
15-
test: (_root, args) => args.input,
17+
test: () => 'test',
1618
}
1719
},
1820
});
1921

22+
const stitchedSchema = stitchSchemas({
23+
subschemas: [schema]
24+
});
25+
2026
const result = await graphql(
21-
schema,
27+
stitchedSchema,
2228
`
2329
query {
2430
... on Query @defer {
25-
test(input: "test")
31+
test
2632
}
2733
}
2834
`,
2935
);
3036

3137
const results = [];
32-
if (result[Symbol.asyncIterator]) {
38+
if (isAsyncIterable(result)) {
3339
for await (let patch of result) {
3440
results.push(patch);
3541
}
@@ -46,6 +52,63 @@ describe('defer support', () => {
4652
hasNext: false,
4753
path: [],
4854
});
55+
});
4956

57+
test('should work for nested fields', async () => {
58+
const schema = makeExecutableSchema({
59+
typeDefs: `
60+
type Object {
61+
test: String
62+
}
63+
type Query {
64+
object: Object
65+
}
66+
`,
67+
resolvers: {
68+
Object: {
69+
test: () => 'test',
70+
},
71+
Query: {
72+
object: () => ({}),
73+
}
74+
},
75+
});
76+
77+
const stitchedSchema = stitchSchemas({
78+
subschemas: [schema]
79+
});
80+
81+
const result = await graphql(
82+
stitchedSchema,
83+
`
84+
query {
85+
object {
86+
... on Object @defer {
87+
test
88+
}
89+
}
90+
}
91+
`,
92+
);
93+
94+
const results = [];
95+
if (isAsyncIterable(result)) {
96+
for await (let patch of result) {
97+
results.push(patch);
98+
}
99+
}
100+
101+
expect(results[0]).toEqual({
102+
data: { object: {} },
103+
hasNext: true,
104+
});
105+
expect(results[1]).toEqual({
106+
data: {
107+
test: 'test'
108+
},
109+
hasNext: false,
110+
path: ['object'],
111+
});
50112
});
51113
});
114+

0 commit comments

Comments
 (0)