Skip to content

Commit

Permalink
Support returning async iterables from resolver functions (graphql#2712)
Browse files Browse the repository at this point in the history
Co-authored-by: Ivan Goncharov <ivan.goncharov.ua@gmail.com>
  • Loading branch information
robrichard and IvanGoncharov committed Oct 4, 2020
1 parent 7e79bbe commit 6dcba93
Show file tree
Hide file tree
Showing 2 changed files with 103 additions and 1 deletion.
41 changes: 41 additions & 0 deletions src/execution/__tests__/lists-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,47 @@ describe('Execute: Accepts any iterable as list value', () => {
});
});

describe('Execute: Accepts async iterables as list value', () => {
function complete(rootValue: mixed) {
return execute({
schema: buildSchema('type Query { listField: [String] }'),
document: parse('{ listField }'),
rootValue,
});
}

it('Accepts an AsyncGenerator function as a List value', async () => {
async function* listField() {
yield await 'two';
yield await 4;
yield await false;
}

expect(await complete({ listField })).to.deep.equal({
data: { listField: ['two', '4', 'false'] },
});
});

it('Handles an AsyncGenerator function that throws', async () => {
async function* listField() {
yield await 'two';
yield await 4;
throw new Error('bad');
}

expect(await complete({ listField })).to.deep.equal({
data: { listField: ['two', '4', null] },
errors: [
{
message: 'bad',
locations: [{ line: 1, column: 3 }],
path: ['listField', 2],
},
],
});
});
});

describe('Execute: Handles list nullability', () => {
async function complete(args: {| listField: mixed, as: string |}) {
const { listField, as } = args;
Expand Down
63 changes: 62 additions & 1 deletion src/execution/execute.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import arrayFrom from '../polyfills/arrayFrom';
import { SYMBOL_ASYNC_ITERATOR } from '../polyfills/symbols';

import type { Path } from '../jsutils/Path';
import type { ObjMap } from '../jsutils/ObjMap';
Expand All @@ -8,6 +9,7 @@ import memoize3 from '../jsutils/memoize3';
import invariant from '../jsutils/invariant';
import devAssert from '../jsutils/devAssert';
import isPromise from '../jsutils/isPromise';
import isAsyncIterable from '../jsutils/isAsyncIterable';
import isObjectLike from '../jsutils/isObjectLike';
import isCollection from '../jsutils/isCollection';
import promiseReduce from '../jsutils/promiseReduce';
Expand Down Expand Up @@ -855,6 +857,49 @@ function completeValue(
);
}

/**
* Complete a async iterator value by completing the result and calling
* recursively until all the results are completed.
*/
function completeAsyncIteratorValue(
exeContext: ExecutionContext,
itemType: GraphQLOutputType,
fieldNodes: $ReadOnlyArray<FieldNode>,
info: GraphQLResolveInfo,
path: Path,
index: number,
completedResults: Array<mixed>,
iterator: AsyncIterator<mixed>,
): Promise<$ReadOnlyArray<mixed>> {
const fieldPath = addPath(path, index, undefined);
return iterator.next().then(
({ value, done }) => {
if (done) {
return completedResults;
}
completedResults.push(
completeValue(exeContext, itemType, fieldNodes, info, fieldPath, value),
);
return completeAsyncIteratorValue(
exeContext,
itemType,
fieldNodes,
info,
path,
index + 1,
completedResults,
iterator,
);
},
(rawError) => {
completedResults.push(null);
const error = locatedError(rawError, fieldNodes, pathToArray(fieldPath));
handleFieldError(error, itemType, exeContext);
return completedResults;
},
);
}

/**
* Complete a list value by completing each item in the list with the
* inner type
Expand All @@ -867,6 +912,23 @@ function completeListValue(
path: Path,
result: mixed,
): PromiseOrValue<$ReadOnlyArray<mixed>> {
const itemType = returnType.ofType;

if (isAsyncIterable(result)) {
const iterator = result[SYMBOL_ASYNC_ITERATOR]();

return completeAsyncIteratorValue(
exeContext,
itemType,
fieldNodes,
info,
path,
0,
[],
iterator,
);
}

if (!isCollection(result)) {
throw new GraphQLError(
`Expected Iterable, but did not find one for field "${info.parentType.name}.${info.fieldName}".`,
Expand All @@ -875,7 +937,6 @@ function completeListValue(

// This is specified as a simple map, however we're optimizing the path
// where the list contains no Promises by avoiding creating another Promise.
const itemType = returnType.ofType;
let containsPromise = false;
const completedResults = arrayFrom(result, (item, index) => {
// No need to modify the info object containing the path,
Expand Down

0 comments on commit 6dcba93

Please sign in to comment.