Skip to content

Commit c1fe951

Browse files
authored
refactor: subscribe: introduce buildPerEventExecutionContext (#3639)
= introduces `buildPerEventExecutionContext` that creates an `ExecutionContext` for each subscribe event from the original `ExecutionContext` used to create the event stream = `subscribe` now directly builds the `ExecutionContext` instead of relying on `createSourceEventStream` = introduces `createSourceEventStreamImpl` and `executeImpl` functions that operate on the built `ExecutionContext` rather the `ExecutionArgs` = `subscribe` calls the `createSourceEventStreamImpl` function on the original context and eventuallys calls `executeImpl` on the per event context created by `buildEventExecutionContext`. Motivation: 1. remove unnecessary `buildExecutionContext` call, reducing duplicate work 2. paves the way for easily enhancing the `buildPerEventExecutionContext` to add a new `perEventContextFactory` argument to augment the context argument passed to resolvers as need per event.
1 parent 467be3e commit c1fe951

File tree

2 files changed

+50
-15
lines changed

2 files changed

+50
-15
lines changed

src/execution/__tests__/subscribe-test.ts

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import { GraphQLList, GraphQLObjectType } from '../../type/definition';
1414
import { GraphQLBoolean, GraphQLInt, GraphQLString } from '../../type/scalars';
1515
import { GraphQLSchema } from '../../type/schema';
1616

17-
import type { ExecutionResult } from '../execute';
17+
import type { ExecutionArgs, ExecutionResult } from '../execute';
1818
import { createSourceEventStream, subscribe } from '../execute';
1919

2020
import { SimplePubSub } from './simplePubSub';
@@ -189,9 +189,15 @@ function subscribeWithBadFn(
189189
});
190190
const document = parse('subscription { foo }');
191191

192+
return subscribeWithBadArgs({ schema, document });
193+
}
194+
195+
function subscribeWithBadArgs(
196+
args: ExecutionArgs,
197+
): PromiseOrValue<ExecutionResult | AsyncIterable<unknown>> {
192198
return expectEqualPromisesOrValues(
193-
subscribe({ schema, document }),
194-
createSourceEventStream({ schema, document }),
199+
subscribe(args),
200+
createSourceEventStream(args),
195201
);
196202
}
197203

@@ -394,7 +400,7 @@ describe('Subscription Initialization Phase', () => {
394400
const schema = new GraphQLSchema({ query: DummyQueryType });
395401
const document = parse('subscription { unknownField }');
396402

397-
const result = subscribe({ schema, document });
403+
const result = subscribeWithBadArgs({ schema, document });
398404
expectJSON(result).toDeepEqual({
399405
errors: [
400406
{
@@ -418,7 +424,7 @@ describe('Subscription Initialization Phase', () => {
418424
});
419425
const document = parse('subscription { unknownField }');
420426

421-
const result = subscribe({ schema, document });
427+
const result = subscribeWithBadArgs({ schema, document });
422428
expectJSON(result).toDeepEqual({
423429
errors: [
424430
{
@@ -441,7 +447,7 @@ describe('Subscription Initialization Phase', () => {
441447
});
442448

443449
// @ts-expect-error
444-
expect(() => subscribe({ schema, document: {} })).to.throw();
450+
expect(() => subscribeWithBadArgs({ schema, document: {} })).to.throw();
445451
});
446452

447453
it('throws an error if subscribe does not return an iterator', async () => {
@@ -526,7 +532,7 @@ describe('Subscription Initialization Phase', () => {
526532

527533
// If we receive variables that cannot be coerced correctly, subscribe() will
528534
// resolve to an ExecutionResult that contains an informative error description.
529-
const result = subscribe({ schema, document, variableValues });
535+
const result = subscribeWithBadArgs({ schema, document, variableValues });
530536
expectJSON(result).toDeepEqual({
531537
errors: [
532538
{

src/execution/execute.ts

Lines changed: 37 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,12 @@ export function execute(args: ExecutionArgs): PromiseOrValue<ExecutionResult> {
174174
return { errors: exeContext };
175175
}
176176

177+
return executeImpl(exeContext);
178+
}
179+
180+
function executeImpl(
181+
exeContext: ExecutionContext,
182+
): PromiseOrValue<ExecutionResult> {
177183
// Return a Promise that will eventually resolve to the data described by
178184
// The "Response" section of the GraphQL specification.
179185
//
@@ -319,6 +325,17 @@ export function buildExecutionContext(
319325
};
320326
}
321327

328+
function buildPerEventExecutionContext(
329+
exeContext: ExecutionContext,
330+
payload: unknown,
331+
): ExecutionContext {
332+
return {
333+
...exeContext,
334+
rootValue: payload,
335+
errors: [],
336+
};
337+
}
338+
322339
/**
323340
* Implements the "Executing operations" section of the spec.
324341
*/
@@ -1017,20 +1034,29 @@ export function subscribe(
10171034
): PromiseOrValue<
10181035
AsyncGenerator<ExecutionResult, void, void> | ExecutionResult
10191036
> {
1020-
const resultOrStream = createSourceEventStream(args);
1037+
// If a valid execution context cannot be created due to incorrect arguments,
1038+
// a "Response" with only errors is returned.
1039+
const exeContext = buildExecutionContext(args);
1040+
1041+
// Return early errors if execution context failed.
1042+
if (!('schema' in exeContext)) {
1043+
return { errors: exeContext };
1044+
}
1045+
1046+
const resultOrStream = createSourceEventStreamImpl(exeContext);
10211047

10221048
if (isPromise(resultOrStream)) {
10231049
return resultOrStream.then((resolvedResultOrStream) =>
1024-
mapSourceToResponse(resolvedResultOrStream, args),
1050+
mapSourceToResponse(exeContext, resolvedResultOrStream),
10251051
);
10261052
}
10271053

1028-
return mapSourceToResponse(resultOrStream, args);
1054+
return mapSourceToResponse(exeContext, resultOrStream);
10291055
}
10301056

10311057
function mapSourceToResponse(
1058+
exeContext: ExecutionContext,
10321059
resultOrStream: ExecutionResult | AsyncIterable<unknown>,
1033-
args: ExecutionArgs,
10341060
): PromiseOrValue<
10351061
AsyncGenerator<ExecutionResult, void, void> | ExecutionResult
10361062
> {
@@ -1045,10 +1071,7 @@ function mapSourceToResponse(
10451071
// "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the
10461072
// "ExecuteQuery" algorithm, for which `execute` is also used.
10471073
return mapAsyncIterator(resultOrStream, (payload: unknown) =>
1048-
execute({
1049-
...args,
1050-
rootValue: payload,
1051-
}),
1074+
executeImpl(buildPerEventExecutionContext(exeContext, payload)),
10521075
);
10531076
}
10541077

@@ -1092,6 +1115,12 @@ export function createSourceEventStream(
10921115
return { errors: exeContext };
10931116
}
10941117

1118+
return createSourceEventStreamImpl(exeContext);
1119+
}
1120+
1121+
function createSourceEventStreamImpl(
1122+
exeContext: ExecutionContext,
1123+
): PromiseOrValue<AsyncIterable<unknown> | ExecutionResult> {
10951124
try {
10961125
const eventStream = executeSubscription(exeContext);
10971126
if (isPromise(eventStream)) {

0 commit comments

Comments
 (0)