Skip to content

Add support for defer and stream directives (Feedback is welcome) #2839

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 8 commits into from
566 changes: 566 additions & 0 deletions src/execution/__tests__/defer-test.ts

Large diffs are not rendered by default.

145 changes: 145 additions & 0 deletions src/execution/__tests__/flattenAsyncIterator-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import { expect } from 'chai';
import { describe, it } from 'mocha';

import { flattenAsyncIterator } from '../flattenAsyncIterator';

describe('flattenAsyncIterator', () => {
it('does not modify an already flat async generator', async () => {
async function* source() {
yield await Promise.resolve(1);
yield await Promise.resolve(2);
yield await Promise.resolve(3);
}

const result = flattenAsyncIterator(source());

expect(await result.next()).to.deep.equal({ value: 1, done: false });
expect(await result.next()).to.deep.equal({ value: 2, done: false });
expect(await result.next()).to.deep.equal({ value: 3, done: false });
expect(await result.next()).to.deep.equal({
value: undefined,
done: true,
});
});

it('does not modify an already flat async iterator', async () => {
const items = [1, 2, 3];

const iterator: any = {
[Symbol.asyncIterator]() {
return this;
},
next() {
return Promise.resolve({
done: items.length === 0,
value: items.shift(),
});
},
};

const result = flattenAsyncIterator(iterator);

expect(await result.next()).to.deep.equal({ value: 1, done: false });
expect(await result.next()).to.deep.equal({ value: 2, done: false });
expect(await result.next()).to.deep.equal({ value: 3, done: false });
expect(await result.next()).to.deep.equal({
value: undefined,
done: true,
});
});

it('flatten nested async generators', async () => {
async function* source() {
yield await Promise.resolve(1);
yield await Promise.resolve(2);
yield await Promise.resolve(
(async function* nested(): AsyncGenerator<number, void, void> {
yield await Promise.resolve(2.1);
yield await Promise.resolve(2.2);
})(),
);
yield await Promise.resolve(3);
}

const doubles = flattenAsyncIterator(source());

const result = [];
for await (const x of doubles) {
result.push(x);
}
expect(result).to.deep.equal([1, 2, 2.1, 2.2, 3]);
});

it('allows returning early from a nested async generator', async () => {
async function* source() {
yield await Promise.resolve(1);
yield await Promise.resolve(2);
yield await Promise.resolve(
(async function* nested(): AsyncGenerator<number, void, void> {
yield await Promise.resolve(2.1); /* c8 ignore start */
// Not reachable, early return
yield await Promise.resolve(2.2);
})(),
);
// Not reachable, early return
yield await Promise.resolve(3);
}
/* c8 ignore stop */

const doubles = flattenAsyncIterator(source());

expect(await doubles.next()).to.deep.equal({ value: 1, done: false });
expect(await doubles.next()).to.deep.equal({ value: 2, done: false });
expect(await doubles.next()).to.deep.equal({ value: 2.1, done: false });

// Early return
expect(await doubles.return()).to.deep.equal({
value: undefined,
done: true,
});

// Subsequent next calls
expect(await doubles.next()).to.deep.equal({
value: undefined,
done: true,
});
expect(await doubles.next()).to.deep.equal({
value: undefined,
done: true,
});
});

it('allows throwing errors from a nested async generator', async () => {
async function* source() {
yield await Promise.resolve(1);
yield await Promise.resolve(2);
yield await Promise.resolve(
(async function* nested(): AsyncGenerator<number, void, void> {
yield await Promise.resolve(2.1); /* c8 ignore start */
// Not reachable, early return
yield await Promise.resolve(2.2);
})(),
);
// Not reachable, early return
yield await Promise.resolve(3);
}
/* c8 ignore stop */

const doubles = flattenAsyncIterator(source());

expect(await doubles.next()).to.deep.equal({ value: 1, done: false });
expect(await doubles.next()).to.deep.equal({ value: 2, done: false });
expect(await doubles.next()).to.deep.equal({ value: 2.1, done: false });

// Throw error
let caughtError;
try {
await doubles.throw('ouch'); /* c8 ignore start */
// Not reachable, always throws
/* c8 ignore stop */
} catch (e) {
caughtError = e;
}
expect(caughtError).to.equal('ouch');
});
});
6 changes: 4 additions & 2 deletions src/execution/__tests__/lists-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { GraphQLSchema } from '../../type/schema';

import { buildSchema } from '../../utilities/buildASTSchema';

import type { ExecutionResult } from '../execute';
import type { AsyncExecutionResult, ExecutionResult } from '../execute';
import { execute, executeSync } from '../execute';

describe('Execute: Accepts any iterable as list value', () => {
Expand Down Expand Up @@ -85,7 +85,9 @@ describe('Execute: Accepts async iterables as list value', () => {

function completeObjectList(
resolve: GraphQLFieldResolver<{ index: number }, unknown>,
): PromiseOrValue<ExecutionResult> {
): PromiseOrValue<
ExecutionResult | AsyncGenerator<AsyncExecutionResult, void, void>
> {
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
Expand Down
129 changes: 128 additions & 1 deletion src/execution/__tests__/mutations-test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { expect } from 'chai';
import { assert, expect } from 'chai';
import { describe, it } from 'mocha';

import { expectJSON } from '../../__testUtils__/expectJSON';
import { resolveOnNextTick } from '../../__testUtils__/resolveOnNextTick';

import { isAsyncIterable } from '../../jsutils/isAsyncIterable';

import { parse } from '../../language/parser';

import { GraphQLObjectType } from '../../type/definition';
Expand Down Expand Up @@ -50,6 +52,13 @@ class Root {
const numberHolderType = new GraphQLObjectType({
fields: {
theNumber: { type: GraphQLInt },
promiseToGetTheNumber: {
type: GraphQLInt,
resolve: async (root) => {
await new Promise((resolve) => setTimeout(resolve, 0));
return root.theNumber;
},
},
},
name: 'NumberHolder',
});
Expand Down Expand Up @@ -191,4 +200,122 @@ describe('Execute: Handles mutation execution ordering', () => {
],
});
});
it('Mutation fields with @defer do not block next mutation', async () => {
const document = parse(`
mutation M {
first: promiseToChangeTheNumber(newNumber: 1) {
...DeferFragment @defer(label: "defer-label")
},
second: immediatelyChangeTheNumber(newNumber: 2) {
theNumber
}
}
fragment DeferFragment on NumberHolder {
promiseToGetTheNumber
}
`);

const rootValue = new Root(6);
const mutationResult = await execute({
schema,
document,
rootValue,
});
const patches = [];

assert(isAsyncIterable(mutationResult));
for await (const patch of mutationResult) {
patches.push(patch);
}

expect(patches).to.deep.equal([
{
data: {
first: {},
second: { theNumber: 2 },
},
hasNext: true,
},
{
label: 'defer-label',
path: ['first'],
data: {
promiseToGetTheNumber: 2,
},
hasNext: false,
},
]);
});
it('Mutation inside of a fragment', async () => {
const document = parse(`
mutation M {
...MutationFragment
second: immediatelyChangeTheNumber(newNumber: 2) {
theNumber
}
}
fragment MutationFragment on Mutation {
first: promiseToChangeTheNumber(newNumber: 1) {
theNumber
},
}
`);

const rootValue = new Root(6);
const mutationResult = await execute({ schema, document, rootValue });

expect(mutationResult).to.deep.equal({
data: {
first: { theNumber: 1 },
second: { theNumber: 2 },
},
});
});
it('Mutation with @defer is not executed serially', async () => {
const document = parse(`
mutation M {
...MutationFragment @defer(label: "defer-label")
second: immediatelyChangeTheNumber(newNumber: 2) {
theNumber
}
}
fragment MutationFragment on Mutation {
first: promiseToChangeTheNumber(newNumber: 1) {
theNumber
},
}
`);

const rootValue = new Root(6);
const mutationResult = await execute({
schema,
document,
rootValue,
});
const patches = [];

assert(isAsyncIterable(mutationResult));
for await (const patch of mutationResult) {
patches.push(patch);
}

expect(patches).to.deep.equal([
{
data: {
second: { theNumber: 2 },
},
hasNext: true,
},
{
label: 'defer-label',
path: [],
data: {
first: {
theNumber: 1,
},
},
hasNext: false,
},
]);
});
});
8 changes: 6 additions & 2 deletions src/execution/__tests__/nonnull-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { describe, it } from 'mocha';

import { expectJSON } from '../../__testUtils__/expectJSON';

import type { PromiseOrValue } from '../../jsutils/PromiseOrValue';

import { parse } from '../../language/parser';

import { GraphQLNonNull, GraphQLObjectType } from '../../type/definition';
Expand All @@ -11,7 +13,7 @@ import { GraphQLSchema } from '../../type/schema';

import { buildSchema } from '../../utilities/buildASTSchema';

import type { ExecutionResult } from '../execute';
import type { AsyncExecutionResult, ExecutionResult } from '../execute';
import { execute, executeSync } from '../execute';

const syncError = new Error('sync');
Expand Down Expand Up @@ -109,7 +111,9 @@ const schema = buildSchema(`
function executeQuery(
query: string,
rootValue: unknown,
): ExecutionResult | Promise<ExecutionResult> {
): PromiseOrValue<
ExecutionResult | AsyncGenerator<AsyncExecutionResult, void, void>
> {
return execute({ schema, document: parse(query), rootValue });
}

Expand Down
Loading