Skip to content

Commit eae3bd2

Browse files
committed
add defer/stream support for subscriptions (#7)
# Conflicts: # src/subscription/subscribe.ts
1 parent 46762cc commit eae3bd2

File tree

4 files changed

+347
-17
lines changed

4 files changed

+347
-17
lines changed
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
import { expect } from 'chai';
2+
import { describe, it } from 'mocha';
3+
4+
import { flattenAsyncIterator } from '../flattenAsyncIterator';
5+
6+
describe('flattenAsyncIterator', () => {
7+
it('does not modify an already flat async generator', async () => {
8+
async function* source() {
9+
yield await Promise.resolve(1);
10+
yield await Promise.resolve(2);
11+
yield await Promise.resolve(3);
12+
}
13+
14+
const result = flattenAsyncIterator(source());
15+
16+
expect(await result.next()).to.deep.equal({ value: 1, done: false });
17+
expect(await result.next()).to.deep.equal({ value: 2, done: false });
18+
expect(await result.next()).to.deep.equal({ value: 3, done: false });
19+
expect(await result.next()).to.deep.equal({
20+
value: undefined,
21+
done: true,
22+
});
23+
});
24+
25+
it('does not modify an already flat async iterator', async () => {
26+
const items = [1, 2, 3];
27+
28+
const iterator: any = {
29+
[Symbol.asyncIterator]() {
30+
return this;
31+
},
32+
next() {
33+
return Promise.resolve({
34+
done: items.length === 0,
35+
value: items.shift(),
36+
});
37+
},
38+
};
39+
40+
const result = flattenAsyncIterator(iterator);
41+
42+
expect(await result.next()).to.deep.equal({ value: 1, done: false });
43+
expect(await result.next()).to.deep.equal({ value: 2, done: false });
44+
expect(await result.next()).to.deep.equal({ value: 3, done: false });
45+
expect(await result.next()).to.deep.equal({
46+
value: undefined,
47+
done: true,
48+
});
49+
});
50+
51+
it('flatten nested async generators', async () => {
52+
async function* source() {
53+
yield await Promise.resolve(1);
54+
yield await Promise.resolve(2);
55+
yield await Promise.resolve(
56+
(async function* nested(): AsyncGenerator<number, void, void> {
57+
yield await Promise.resolve(2.1);
58+
yield await Promise.resolve(2.2);
59+
})(),
60+
);
61+
yield await Promise.resolve(3);
62+
}
63+
64+
const doubles = flattenAsyncIterator(source());
65+
66+
const result = [];
67+
for await (const x of doubles) {
68+
result.push(x);
69+
}
70+
expect(result).to.deep.equal([1, 2, 2.1, 2.2, 3]);
71+
});
72+
73+
it('allows returning early from a nested async generator', async () => {
74+
async function* source() {
75+
yield await Promise.resolve(1);
76+
yield await Promise.resolve(2);
77+
yield await Promise.resolve(
78+
(async function* nested(): AsyncGenerator<number, void, void> {
79+
yield await Promise.resolve(2.1); /* c8 ignore start */
80+
// Not reachable, early return
81+
yield await Promise.resolve(2.2);
82+
})(),
83+
);
84+
// Not reachable, early return
85+
yield await Promise.resolve(3);
86+
}
87+
/* c8 ignore stop */
88+
89+
const doubles = flattenAsyncIterator(source());
90+
91+
expect(await doubles.next()).to.deep.equal({ value: 1, done: false });
92+
expect(await doubles.next()).to.deep.equal({ value: 2, done: false });
93+
expect(await doubles.next()).to.deep.equal({ value: 2.1, done: false });
94+
95+
// Early return
96+
expect(await doubles.return()).to.deep.equal({
97+
value: undefined,
98+
done: true,
99+
});
100+
101+
// Subsequent next calls
102+
expect(await doubles.next()).to.deep.equal({
103+
value: undefined,
104+
done: true,
105+
});
106+
expect(await doubles.next()).to.deep.equal({
107+
value: undefined,
108+
done: true,
109+
});
110+
});
111+
112+
it('allows throwing errors from a nested async generator', async () => {
113+
async function* source() {
114+
yield await Promise.resolve(1);
115+
yield await Promise.resolve(2);
116+
yield await Promise.resolve(
117+
(async function* nested(): AsyncGenerator<number, void, void> {
118+
yield await Promise.resolve(2.1); /* c8 ignore start */
119+
// Not reachable, early return
120+
yield await Promise.resolve(2.2);
121+
})(),
122+
);
123+
// Not reachable, early return
124+
yield await Promise.resolve(3);
125+
}
126+
/* c8 ignore stop */
127+
128+
const doubles = flattenAsyncIterator(source());
129+
130+
expect(await doubles.next()).to.deep.equal({ value: 1, done: false });
131+
expect(await doubles.next()).to.deep.equal({ value: 2, done: false });
132+
expect(await doubles.next()).to.deep.equal({ value: 2.1, done: false });
133+
134+
// Throw error
135+
let caughtError;
136+
try {
137+
await doubles.throw('ouch'); /* c8 ignore start */
138+
// Not reachable, always throws
139+
/* c8 ignore stop */
140+
} catch (e) {
141+
caughtError = e;
142+
}
143+
expect(caughtError).to.equal('ouch');
144+
});
145+
});

src/execution/__tests__/subscribe-test.ts

Lines changed: 146 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -82,17 +82,22 @@ const emailSchema = new GraphQLSchema({
8282
}),
8383
});
8484

85-
function createSubscription(pubsub: SimplePubSub<Email>) {
85+
function createSubscription(
86+
pubsub: SimplePubSub<Email>,
87+
variableValues?: { readonly [variable: string]: unknown },
88+
) {
8689
const document = parse(`
87-
subscription ($priority: Int = 0) {
90+
subscription ($priority: Int = 0, $shouldDefer: Boolean = false) {
8891
importantEmail(priority: $priority) {
8992
email {
9093
from
9194
subject
9295
}
93-
inbox {
94-
unread
95-
total
96+
... @defer(if: $shouldDefer) {
97+
inbox {
98+
unread
99+
total
100+
}
96101
}
97102
}
98103
}
@@ -122,7 +127,12 @@ function createSubscription(pubsub: SimplePubSub<Email>) {
122127
}),
123128
};
124129

125-
return subscribe({ schema: emailSchema, document, rootValue: data });
130+
return subscribe({
131+
schema: emailSchema,
132+
document,
133+
rootValue: data,
134+
variableValues,
135+
});
126136
}
127137

128138
// TODO: consider adding this method to testUtils (with tests)
@@ -704,6 +714,136 @@ describe('Subscription Publish Phase', () => {
704714
});
705715
});
706716

717+
it('produces additional payloads for subscriptions with @defer', async () => {
718+
const pubsub = new SimplePubSub<Email>();
719+
const subscription = await createSubscription(pubsub, {
720+
shouldDefer: true,
721+
});
722+
assert(isAsyncIterable(subscription));
723+
// Wait for the next subscription payload.
724+
const payload = subscription.next();
725+
726+
// A new email arrives!
727+
expect(
728+
pubsub.emit({
729+
from: 'yuzhi@graphql.org',
730+
subject: 'Alright',
731+
message: 'Tests are good',
732+
unread: true,
733+
}),
734+
).to.equal(true);
735+
736+
// The previously waited on payload now has a value.
737+
expect(await payload).to.deep.equal({
738+
done: false,
739+
value: {
740+
data: {
741+
importantEmail: {
742+
email: {
743+
from: 'yuzhi@graphql.org',
744+
subject: 'Alright',
745+
},
746+
},
747+
},
748+
hasNext: true,
749+
},
750+
});
751+
752+
// Wait for the next payload from @defer
753+
expect(await subscription.next()).to.deep.equal({
754+
done: false,
755+
value: {
756+
data: {
757+
inbox: {
758+
unread: 1,
759+
total: 2,
760+
},
761+
},
762+
path: ['importantEmail'],
763+
hasNext: false,
764+
},
765+
});
766+
767+
// Another new email arrives, after all incrementally delivered payloads are received.
768+
expect(
769+
pubsub.emit({
770+
from: 'hyo@graphql.org',
771+
subject: 'Tools',
772+
message: 'I <3 making things',
773+
unread: true,
774+
}),
775+
).to.equal(true);
776+
777+
// The next waited on payload will have a value.
778+
expect(await subscription.next()).to.deep.equal({
779+
done: false,
780+
value: {
781+
data: {
782+
importantEmail: {
783+
email: {
784+
from: 'hyo@graphql.org',
785+
subject: 'Tools',
786+
},
787+
},
788+
},
789+
hasNext: true,
790+
},
791+
});
792+
793+
// Another new email arrives, before the incrementally delivered payloads from the last email was received.
794+
expect(
795+
pubsub.emit({
796+
from: 'adam@graphql.org',
797+
subject: 'Important',
798+
message: 'Read me please',
799+
unread: true,
800+
}),
801+
).to.equal(true);
802+
803+
// Deferred payload from previous event is received.
804+
expect(await subscription.next()).to.deep.equal({
805+
done: false,
806+
value: {
807+
data: {
808+
inbox: {
809+
unread: 2,
810+
total: 3,
811+
},
812+
},
813+
path: ['importantEmail'],
814+
hasNext: false,
815+
},
816+
});
817+
818+
// Next payload from last event
819+
expect(await subscription.next()).to.deep.equal({
820+
done: false,
821+
value: {
822+
data: {
823+
importantEmail: {
824+
email: {
825+
from: 'adam@graphql.org',
826+
subject: 'Important',
827+
},
828+
},
829+
},
830+
hasNext: true,
831+
},
832+
});
833+
834+
// The client disconnects before the deferred payload is consumed.
835+
expect(await subscription.return()).to.deep.equal({
836+
done: true,
837+
value: undefined,
838+
});
839+
840+
// Awaiting a subscription after closing it results in completed results.
841+
expect(await subscription.next()).to.deep.equal({
842+
done: true,
843+
value: undefined,
844+
});
845+
});
846+
707847
it('produces a payload when there are multiple events', async () => {
708848
const pubsub = new SimplePubSub<Email>();
709849
const subscription = createSubscription(pubsub);

src/execution/execute.ts

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ import {
5353
collectFields,
5454
collectSubfields as _collectSubfields,
5555
} from './collectFields';
56+
import { flattenAsyncIterator } from './flattenAsyncIterator';
5657
import { mapAsyncIterator } from './mapAsyncIterator';
5758
import {
5859
getArgumentValues,
@@ -1396,17 +1397,11 @@ function mapSourceToResponse(
13961397
// the GraphQL specification. The `execute` function provides the
13971398
// "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the
13981399
// "ExecuteQuery" algorithm, for which `execute` is also used.
1399-
return mapAsyncIterator(resultOrStream, (payload: unknown) => {
1400-
const executionResult = execute({ ...args, rootValue: payload });
1401-
/* c8 ignore next 6 */
1402-
// TODO: implement support for defer/stream in subscriptions
1403-
if (isAsyncIterable(executionResult)) {
1404-
throw new Error(
1405-
'TODO: implement support for defer/stream in subscriptions',
1406-
);
1407-
}
1408-
return executionResult as PromiseOrValue<ExecutionResult>;
1409-
});
1400+
return flattenAsyncIterator<ExecutionResult, AsyncExecutionResult>(
1401+
mapAsyncIterator(resultOrStream, (payload: unknown) =>
1402+
execute({ ...args, rootValue: payload }),
1403+
),
1404+
);
14101405
}
14111406

14121407
/**

0 commit comments

Comments
 (0)