@graphql-tools/executor 0.0.1 → 0.0.2-alpha-20221029152711-14f4f7a7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/cjs/directives/defer.js +23 -0
  2. package/cjs/directives/index.js +5 -0
  3. package/cjs/directives/stream.js +28 -0
  4. package/cjs/execution/AccumulatorMap.js +21 -0
  5. package/cjs/execution/collectFields.js +126 -0
  6. package/cjs/execution/execute.js +656 -109
  7. package/cjs/execution/flattenAsyncIterable.js +91 -0
  8. package/cjs/execution/invariant.js +9 -0
  9. package/cjs/execution/promiseForObject.js +21 -0
  10. package/cjs/index.js +1 -0
  11. package/esm/directives/defer.js +20 -0
  12. package/esm/directives/index.js +2 -0
  13. package/esm/directives/stream.js +25 -0
  14. package/esm/execution/AccumulatorMap.js +17 -0
  15. package/esm/execution/collectFields.js +122 -0
  16. package/esm/execution/execute.js +653 -108
  17. package/esm/execution/flattenAsyncIterable.js +87 -0
  18. package/esm/execution/invariant.js +5 -0
  19. package/esm/execution/promiseForObject.js +17 -0
  20. package/esm/index.js +1 -0
  21. package/package.json +2 -2
  22. package/typings/directives/defer.d.cts +5 -0
  23. package/typings/directives/defer.d.ts +5 -0
  24. package/typings/directives/index.d.cts +2 -0
  25. package/typings/directives/index.d.ts +2 -0
  26. package/typings/directives/stream.d.cts +5 -0
  27. package/typings/directives/stream.d.ts +5 -0
  28. package/typings/execution/AccumulatorMap.d.cts +7 -0
  29. package/typings/execution/AccumulatorMap.d.ts +7 -0
  30. package/typings/execution/collectFields.d.cts +32 -0
  31. package/typings/execution/collectFields.d.ts +32 -0
  32. package/typings/execution/execute.d.cts +167 -22
  33. package/typings/execution/execute.d.ts +167 -22
  34. package/typings/execution/flattenAsyncIterable.d.cts +7 -0
  35. package/typings/execution/flattenAsyncIterable.d.ts +7 -0
  36. package/typings/execution/invariant.d.cts +1 -0
  37. package/typings/execution/invariant.d.ts +1 -0
  38. package/typings/execution/promiseForObject.d.cts +12 -0
  39. package/typings/execution/promiseForObject.d.ts +12 -0
  40. package/typings/index.d.cts +1 -0
  41. package/typings/index.d.ts +1 -0
  42. package/cjs/execution/subscribe.js +0 -158
  43. package/esm/execution/subscribe.js +0 -153
  44. package/typings/execution/subscribe.d.cts +0 -59
  45. package/typings/execution/subscribe.d.ts +0 -59
@@ -1,5 +1,6 @@
1
- import { GraphQLFormattedError, GraphQLError, FieldNode, FragmentDefinitionNode, OperationDefinitionNode, GraphQLField, GraphQLFieldResolver, GraphQLObjectType, GraphQLResolveInfo, GraphQLTypeResolver, GraphQLSchema } from 'graphql';
2
- import { Maybe, Path, MaybePromise, ExecutionResult } from '@graphql-tools/utils';
1
+ import { GraphQLFormattedError, FieldNode, FragmentDefinitionNode, OperationDefinitionNode, GraphQLField, GraphQLFieldResolver, GraphQLObjectType, GraphQLResolveInfo, GraphQLTypeResolver, GraphQLSchema } from 'graphql';
2
+ import type { GraphQLError } from 'graphql';
3
+ import { Path, Maybe, MaybePromise, ExecutionResult } from '@graphql-tools/utils';
3
4
  import { TypedDocumentNode } from '@graphql-typed-document-node/core';
4
5
  /**
5
6
  * Terminology
@@ -26,25 +27,72 @@ import { TypedDocumentNode } from '@graphql-typed-document-node/core';
26
27
  * Namely, schema of the type system that is currently executing,
27
28
  * and the fragments defined in the query document
28
29
  */
29
- export interface ExecutionContext<TContext = any> {
30
+ export interface ExecutionContext<TVariables = any, TContext = any> {
30
31
  schema: GraphQLSchema;
31
32
  fragments: Record<string, FragmentDefinitionNode>;
32
33
  rootValue: unknown;
33
34
  contextValue: TContext;
34
35
  operation: OperationDefinitionNode;
35
- variableValues: {
36
- [variable: string]: unknown;
37
- };
36
+ variableValues: TVariables;
38
37
  fieldResolver: GraphQLFieldResolver<any, TContext>;
39
38
  typeResolver: GraphQLTypeResolver<any, TContext>;
40
39
  subscribeFieldResolver: GraphQLFieldResolver<any, TContext>;
41
40
  errors: Array<GraphQLError>;
41
+ subsequentPayloads: Set<AsyncPayloadRecord>;
42
42
  }
43
- export interface FormattedExecutionResult<TData = any, TExtensions = any> {
43
+ export interface FormattedExecutionResult<TData = Record<string, unknown>, TExtensions = Record<string, unknown>> {
44
44
  errors?: ReadonlyArray<GraphQLFormattedError>;
45
45
  data?: TData | null;
46
46
  extensions?: TExtensions;
47
47
  }
48
+ export interface ExperimentalIncrementalExecutionResults<TData = Record<string, unknown>, TExtensions = Record<string, unknown>> {
49
+ initialResult: InitialIncrementalExecutionResult<TData, TExtensions>;
50
+ subsequentResults: AsyncGenerator<SubsequentIncrementalExecutionResult<TData, TExtensions>, void, void>;
51
+ }
52
+ export interface InitialIncrementalExecutionResult<TData = Record<string, unknown>, TExtensions = Record<string, unknown>> extends ExecutionResult<TData, TExtensions> {
53
+ hasNext: boolean;
54
+ incremental?: ReadonlyArray<IncrementalResult<TData, TExtensions>>;
55
+ extensions?: TExtensions;
56
+ }
57
+ export interface FormattedInitialIncrementalExecutionResult<TData = Record<string, unknown>, TExtensions = Record<string, unknown>> extends FormattedExecutionResult<TData, TExtensions> {
58
+ hasNext: boolean;
59
+ incremental?: ReadonlyArray<FormattedIncrementalResult<TData, TExtensions>>;
60
+ extensions?: TExtensions;
61
+ }
62
+ export interface SubsequentIncrementalExecutionResult<TData = Record<string, unknown>, TExtensions = Record<string, unknown>> {
63
+ hasNext: boolean;
64
+ incremental?: ReadonlyArray<IncrementalResult<TData, TExtensions>>;
65
+ extensions?: TExtensions;
66
+ }
67
+ export interface FormattedSubsequentIncrementalExecutionResult<TData = Record<string, unknown>, TExtensions = Record<string, unknown>> {
68
+ hasNext: boolean;
69
+ incremental?: ReadonlyArray<FormattedIncrementalResult<TData, TExtensions>>;
70
+ extensions?: TExtensions;
71
+ }
72
+ export interface IncrementalDeferResult<TData = Record<string, unknown>, TExtensions = Record<string, unknown>> extends ExecutionResult<TData, TExtensions> {
73
+ path?: ReadonlyArray<string | number>;
74
+ label?: string;
75
+ }
76
+ export interface FormattedIncrementalDeferResult<TData = Record<string, unknown>, TExtensions = Record<string, unknown>> extends FormattedExecutionResult<TData, TExtensions> {
77
+ path?: ReadonlyArray<string | number>;
78
+ label?: string;
79
+ }
80
+ export interface IncrementalStreamResult<TData = Array<unknown>, TExtensions = Record<string, unknown>> {
81
+ errors?: ReadonlyArray<GraphQLError>;
82
+ items?: TData | null;
83
+ path?: ReadonlyArray<string | number>;
84
+ label?: string;
85
+ extensions?: TExtensions;
86
+ }
87
+ export interface FormattedIncrementalStreamResult<TData = Array<unknown>, TExtensions = Record<string, unknown>> {
88
+ errors?: ReadonlyArray<GraphQLFormattedError>;
89
+ items?: TData | null;
90
+ path?: ReadonlyArray<string | number>;
91
+ label?: string;
92
+ extensions?: TExtensions;
93
+ }
94
+ export declare type IncrementalResult<TData = Record<string, unknown>, TExtensions = Record<string, unknown>> = IncrementalDeferResult<TData, TExtensions> | IncrementalStreamResult<TData, TExtensions>;
95
+ export declare type FormattedIncrementalResult<TData = Record<string, unknown>, TExtensions = Record<string, unknown>> = FormattedIncrementalDeferResult<TData, TExtensions> | FormattedIncrementalStreamResult<TData, TExtensions>;
48
96
  export interface ExecutionArgs<TData = any, TVariables = any, TContext = any> {
49
97
  schema: GraphQLSchema;
50
98
  document: TypedDocumentNode<TData, TVariables>;
@@ -65,12 +113,27 @@ export interface ExecutionArgs<TData = any, TVariables = any, TContext = any> {
65
113
  *
66
114
  * If the arguments to this function do not result in a legal execution context,
67
115
  * a GraphQLError will be thrown immediately explaining the invalid input.
116
+ *
117
+ * This function does not support incremental delivery (`@defer` and `@stream`).
118
+ * If an operation which would defer or stream data is executed with this
119
+ * function, it will throw or resolve to an object containing an error instead.
120
+ * Use `experimentalExecuteIncrementally` if you want to support incremental
121
+ * delivery.
122
+ */
123
+ export declare function execute<TData = any, TVariables = any, TContext = any>(args: ExecutionArgs<TData, TVariables, TContext>): MaybePromise<ExecutionResult<TData>>;
124
+ /**
125
+ * Implements the "Executing requests" section of the GraphQL specification,
126
+ * including `@defer` and `@stream` as proposed in
127
+ * https://github.com/graphql/graphql-spec/pull/742
128
+ *
129
+ * This function returns a Promise of an ExperimentalIncrementalExecutionResults
130
+ * object. This object either consists of a single ExecutionResult, or an
131
+ * object containing an `initialResult` and a stream of `subsequentResults`.
132
+ *
133
+ * If the arguments to this function do not result in a legal execution context,
134
+ * a GraphQLError will be thrown immediately explaining the invalid input.
68
135
  */
69
- export declare function execute<TData = {
70
- [key: string]: any;
71
- }, TVariables = {
72
- [key: string]: any;
73
- }, TContext = any>(args: ExecutionArgs<TData, TVariables, TContext>): MaybePromise<ExecutionResult<TData>>;
136
+ export declare function experimentalExecuteIncrementally<TData = any, TVariables = any, TContext = any>(args: ExecutionArgs<TData, TVariables, TContext>): MaybePromise<ExecutionResult<TData> | ExperimentalIncrementalExecutionResults<TData>>;
74
137
  /**
75
138
  * Also implements the "Executing requests" section of the GraphQL specification.
76
139
  * However, it guarantees to complete synchronously (or throw an error) assuming
@@ -93,11 +156,7 @@ export declare function assertValidExecutionArguments<TVariables>(schema: GraphQ
93
156
  * TODO: consider no longer exporting this function
94
157
  * @internal
95
158
  */
96
- export declare function buildExecutionContext<TData = {
97
- [key: string]: any;
98
- }, TVariables = {
99
- [key: string]: any;
100
- }, TContext = any>(args: ExecutionArgs<TData, TVariables, TContext>): ReadonlyArray<GraphQLError> | ExecutionContext;
159
+ export declare function buildExecutionContext<TData = any, TVariables = any, TContext = any>(args: ExecutionArgs<TData, TVariables, TContext>): ReadonlyArray<GraphQLError> | ExecutionContext;
101
160
  /**
102
161
  * TODO: consider no longer exporting this function
103
162
  * @internal
@@ -130,19 +189,61 @@ export declare const defaultFieldResolver: GraphQLFieldResolver<unknown, unknown
130
189
  * is not an async iterable.
131
190
  *
132
191
  * If the client-provided arguments to this function do not result in a
133
- * compliant subscription, a GraphQL Response (ExecutionResult) with
134
- * descriptive errors and no data will be returned.
192
+ * compliant subscription, a GraphQL Response (ExecutionResult) with descriptive
193
+ * errors and no data will be returned.
135
194
  *
136
- * If the source stream could not be created due to faulty subscription
137
- * resolver logic or underlying systems, the promise will resolve to a single
195
+ * If the source stream could not be created due to faulty subscription resolver
196
+ * logic or underlying systems, the promise will resolve to a single
138
197
  * ExecutionResult containing `errors` and no `data`.
139
198
  *
140
199
  * If the operation succeeded, the promise resolves to an AsyncIterator, which
141
200
  * yields a stream of ExecutionResults representing the response stream.
142
201
  *
143
- * Accepts either an object with named arguments, or individual arguments.
202
+ * This function does not support incremental delivery (`@defer` and `@stream`).
203
+ * If an operation which would defer or stream data is executed with this
204
+ * function, each `InitialIncrementalExecutionResult` and
205
+ * `SubsequentIncrementalExecutionResult` in the result stream will be replaced
206
+ * with an `ExecutionResult` with a single error stating that defer/stream is
207
+ * not supported. Use `experimentalSubscribeIncrementally` if you want to
208
+ * support incremental delivery.
209
+ *
210
+ * Accepts an object with named arguments.
144
211
  */
145
212
  export declare function subscribe(args: ExecutionArgs): MaybePromise<AsyncIterable<ExecutionResult> | ExecutionResult>;
213
+ /**
214
+ * Implements the "Subscribe" algorithm described in the GraphQL specification,
215
+ * including `@defer` and `@stream` as proposed in
216
+ * https://github.com/graphql/graphql-spec/pull/742
217
+ *
218
+ * Returns a Promise which resolves to either an AsyncIterator (if successful)
219
+ * or an ExecutionResult (error). The promise will be rejected if the schema or
220
+ * other arguments to this function are invalid, or if the resolved event stream
221
+ * is not an async iterable.
222
+ *
223
+ * If the client-provided arguments to this function do not result in a
224
+ * compliant subscription, a GraphQL Response (ExecutionResult) with descriptive
225
+ * errors and no data will be returned.
226
+ *
227
+ * If the source stream could not be created due to faulty subscription resolver
228
+ * logic or underlying systems, the promise will resolve to a single
229
+ * ExecutionResult containing `errors` and no `data`.
230
+ *
231
+ * If the operation succeeded, the promise resolves to an AsyncIterator, which
232
+ * yields a stream of result representing the response stream.
233
+ *
234
+ * Each result may be an ExecutionResult with no `hasNext` (if executing the
235
+ * event did not use `@defer` or `@stream`), or an
236
+ * `InitialIncrementalExecutionResult` or `SubsequentIncrementalExecutionResult`
237
+ * (if executing the event used `@defer` or `@stream`). In the case of
238
+ * incremental execution results, each event produces a single
239
+ * `InitialIncrementalExecutionResult` followed by one or more
240
+ * `SubsequentIncrementalExecutionResult`s; all but the last have `hasNext: true`,
241
+ * and the last has `hasNext: false`. There is no interleaving between results
242
+ * generated from the same original event.
243
+ *
244
+ * Accepts an object with named arguments.
245
+ */
246
+ export declare function experimentalSubscribeIncrementally(args: ExecutionArgs): MaybePromise<AsyncGenerator<ExecutionResult | InitialIncrementalExecutionResult | SubsequentIncrementalExecutionResult, void, void> | ExecutionResult>;
146
247
  /**
147
248
  * Implements the "CreateSourceEventStream" algorithm described in the
148
249
  * GraphQL specification, resolving the subscription source event stream.
@@ -172,6 +273,49 @@ export declare function subscribe(args: ExecutionArgs): MaybePromise<AsyncIterab
172
273
  * "Supporting Subscriptions at Scale" information in the GraphQL specification.
173
274
  */
174
275
  export declare function createSourceEventStream(args: ExecutionArgs): MaybePromise<AsyncIterable<unknown> | ExecutionResult>;
276
+ declare class DeferredFragmentRecord {
277
+ type: 'defer';
278
+ errors: Array<GraphQLError>;
279
+ label: string | undefined;
280
+ path: Array<string | number>;
281
+ promise: Promise<void>;
282
+ data: Record<string, unknown> | null;
283
+ parentContext: AsyncPayloadRecord | undefined;
284
+ isCompleted: boolean;
285
+ _exeContext: ExecutionContext;
286
+ _resolve?: (arg: MaybePromise<Record<string, unknown> | null>) => void;
287
+ constructor(opts: {
288
+ label: string | undefined;
289
+ path: Path | undefined;
290
+ parentContext: AsyncPayloadRecord | undefined;
291
+ exeContext: ExecutionContext;
292
+ });
293
+ addData(data: MaybePromise<Record<string, unknown> | null>): void;
294
+ }
295
+ declare class StreamRecord {
296
+ type: 'stream';
297
+ errors: Array<GraphQLError>;
298
+ label: string | undefined;
299
+ path: Array<string | number>;
300
+ items: Array<unknown> | null;
301
+ promise: Promise<void>;
302
+ parentContext: AsyncPayloadRecord | undefined;
303
+ iterator: AsyncIterator<unknown> | undefined;
304
+ isCompletedIterator?: boolean;
305
+ isCompleted: boolean;
306
+ _exeContext: ExecutionContext;
307
+ _resolve?: (arg: MaybePromise<Array<unknown> | null>) => void;
308
+ constructor(opts: {
309
+ label: string | undefined;
310
+ path: Path | undefined;
311
+ iterator?: AsyncIterator<unknown>;
312
+ parentContext: AsyncPayloadRecord | undefined;
313
+ exeContext: ExecutionContext;
314
+ });
315
+ addItems(items: MaybePromise<Array<unknown> | null>): void;
316
+ setIsCompletedIterator(): void;
317
+ }
318
+ declare type AsyncPayloadRecord = DeferredFragmentRecord | StreamRecord;
175
319
  /**
176
320
  * This method looks up the field on the given type definition.
177
321
  * It has special casing for the three introspection fields,
@@ -184,3 +328,4 @@ export declare function createSourceEventStream(args: ExecutionArgs): MaybePromi
184
328
  * @internal
185
329
  */
186
330
  export declare function getFieldDef(schema: GraphQLSchema, parentType: GraphQLObjectType, fieldNode: FieldNode): Maybe<GraphQLField<unknown, unknown>>;
331
+ export {};
@@ -0,0 +1,7 @@
1
+ declare type AsyncIterableOrGenerator<T> = AsyncGenerator<T, void, void> | AsyncIterable<T>;
2
+ /**
3
+ * Given an AsyncIterable of AsyncIterables, flatten all yielded results into a
4
+ * single AsyncIterable.
5
+ */
6
+ export declare function flattenAsyncIterable<T>(iterable: AsyncIterableOrGenerator<AsyncIterableOrGenerator<T>>): AsyncGenerator<T, void, void>;
7
+ export {};
@@ -0,0 +1,7 @@
1
+ declare type AsyncIterableOrGenerator<T> = AsyncGenerator<T, void, void> | AsyncIterable<T>;
2
+ /**
3
+ * Given an AsyncIterable of AsyncIterables, flatten all yielded results into a
4
+ * single AsyncIterable.
5
+ */
6
+ export declare function flattenAsyncIterable<T>(iterable: AsyncIterableOrGenerator<AsyncIterableOrGenerator<T>>): AsyncGenerator<T, void, void>;
7
+ export {};
@@ -0,0 +1 @@
1
+ export declare function invariant(condition: boolean, message?: string): asserts condition;
@@ -0,0 +1 @@
1
+ export declare function invariant(condition: boolean, message?: string): asserts condition;
@@ -0,0 +1,12 @@
1
+ declare type ResolvedObject<TData> = {
2
+ [TKey in keyof TData]: TData[TKey] extends Promise<infer TValue> ? TValue : TData[TKey];
3
+ };
4
+ /**
5
+ * This function transforms a JS object `Record<string, Promise<T>>` into
6
+ * a `Promise<Record<string, T>>`
7
+ *
8
+ * This is akin to bluebird's `Promise.props`, but implemented only using
9
+ * `Promise.all` so it will work with any implementation of ES6 promises.
10
+ */
11
+ export declare function promiseForObject<TData>(object: TData): Promise<ResolvedObject<TData>>;
12
+ export {};
@@ -0,0 +1,12 @@
1
+ declare type ResolvedObject<TData> = {
2
+ [TKey in keyof TData]: TData[TKey] extends Promise<infer TValue> ? TValue : TData[TKey];
3
+ };
4
+ /**
5
+ * This function transforms a JS object `Record<string, Promise<T>>` into
6
+ * a `Promise<Record<string, T>>`
7
+ *
8
+ * This is akin to bluebird's `Promise.props`, but implemented only using
9
+ * `Promise.all` so it will work with any implementation of ES6 promises.
10
+ */
11
+ export declare function promiseForObject<TData>(object: TData): Promise<ResolvedObject<TData>>;
12
+ export {};
@@ -1 +1,2 @@
1
1
  export * from './execution/index.cjs';
2
+ export * from './directives/index.cjs';
@@ -1 +1,2 @@
1
1
  export * from './execution/index.js';
2
+ export * from './directives/index.js';
@@ -1,158 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createSourceEventStream = exports.subscribe = void 0;
4
- const graphql_1 = require("graphql");
5
- const utils_1 = require("@graphql-tools/utils");
6
- const execute_js_1 = require("./execute.js");
7
- /**
8
- * Implements the "Subscribe" algorithm described in the GraphQL specification.
9
- *
10
- * Returns a Promise which resolves to either an AsyncIterator (if successful)
11
- * or an ExecutionResult (error). The promise will be rejected if the schema or
12
- * other arguments to this function are invalid, or if the resolved event stream
13
- * is not an async iterable.
14
- *
15
- * If the client-provided arguments to this function do not result in a
16
- * compliant subscription, a GraphQL Response (ExecutionResult) with
17
- * descriptive errors and no data will be returned.
18
- *
19
- * If the source stream could not be created due to faulty subscription
20
- * resolver logic or underlying systems, the promise will resolve to a single
21
- * ExecutionResult containing `errors` and no `data`.
22
- *
23
- * If the operation succeeded, the promise resolves to an AsyncIterator, which
24
- * yields a stream of ExecutionResults representing the response stream.
25
- *
26
- * Accepts either an object with named arguments, or individual arguments.
27
- */
28
- async function subscribe(args) {
29
- // Temporary for v15 to v16 migration. Remove in v17
30
- console.assert(arguments.length < 2, 'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.');
31
- const { schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver, } = args;
32
- const resultOrStream = await createSourceEventStream(schema, document, rootValue, contextValue, variableValues, operationName, subscribeFieldResolver);
33
- if (!(0, utils_1.isAsyncIterable)(resultOrStream)) {
34
- return resultOrStream;
35
- }
36
- // For each payload yielded from a subscription, map it over the normal
37
- // GraphQL `execute` function, with `payload` as the rootValue.
38
- // This implements the "MapSourceToResponseEvent" algorithm described in
39
- // the GraphQL specification. The `execute` function provides the
40
- // "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the
41
- // "ExecuteQuery" algorithm, for which `execute` is also used.
42
- const mapSourceToResponse = (payload) => (0, execute_js_1.execute)({
43
- schema,
44
- document,
45
- rootValue: payload,
46
- contextValue,
47
- variableValues,
48
- operationName,
49
- fieldResolver,
50
- });
51
- // Map every source value to a ExecutionResult value as described above.
52
- return (0, utils_1.mapAsyncIterator)(resultOrStream[Symbol.asyncIterator](), mapSourceToResponse);
53
- }
54
- exports.subscribe = subscribe;
55
- /**
56
- * Implements the "CreateSourceEventStream" algorithm described in the
57
- * GraphQL specification, resolving the subscription source event stream.
58
- *
59
- * Returns a Promise which resolves to either an AsyncIterable (if successful)
60
- * or an ExecutionResult (error). The promise will be rejected if the schema or
61
- * other arguments to this function are invalid, or if the resolved event stream
62
- * is not an async iterable.
63
- *
64
- * If the client-provided arguments to this function do not result in a
65
- * compliant subscription, a GraphQL Response (ExecutionResult) with
66
- * descriptive errors and no data will be returned.
67
- *
68
- * If the the source stream could not be created due to faulty subscription
69
- * resolver logic or underlying systems, the promise will resolve to a single
70
- * ExecutionResult containing `errors` and no `data`.
71
- *
72
- * If the operation succeeded, the promise resolves to the AsyncIterable for the
73
- * event stream returned by the resolver.
74
- *
75
- * A Source Event Stream represents a sequence of events, each of which triggers
76
- * a GraphQL execution for that event.
77
- *
78
- * This may be useful when hosting the stateful subscription service in a
79
- * different process or machine than the stateless GraphQL execution engine,
80
- * or otherwise separating these two steps. For more on this, see the
81
- * "Supporting Subscriptions at Scale" information in the GraphQL specification.
82
- */
83
- async function createSourceEventStream(schema, document, rootValue, contextValue, variableValues, operationName, subscribeFieldResolver) {
84
- // If arguments are missing or incorrectly typed, this is an internal
85
- // developer mistake which should throw an early error.
86
- (0, execute_js_1.assertValidExecutionArguments)(schema, document, variableValues);
87
- // If a valid execution context cannot be created due to incorrect arguments,
88
- // a "Response" with only errors is returned.
89
- const exeContext = (0, execute_js_1.buildExecutionContext)({
90
- schema,
91
- document,
92
- rootValue,
93
- contextValue,
94
- variableValues,
95
- operationName,
96
- subscribeFieldResolver,
97
- });
98
- // Return early errors if execution context failed.
99
- if (!('schema' in exeContext)) {
100
- return { errors: exeContext };
101
- }
102
- try {
103
- const eventStream = await executeSubscription(exeContext);
104
- // Assert field returned an event stream, otherwise yield an error.
105
- if (!(0, utils_1.isAsyncIterable)(eventStream)) {
106
- throw new Error('Subscription field must return Async Iterable. ' + `Received: ${(0, utils_1.inspect)(eventStream)}.`);
107
- }
108
- return eventStream;
109
- }
110
- catch (error) {
111
- // If it GraphQLError, report it as an ExecutionResult, containing only errors and no data.
112
- // Otherwise treat the error as a system-class error and re-throw it.
113
- if (error instanceof graphql_1.GraphQLError) {
114
- return { errors: [error] };
115
- }
116
- throw error;
117
- }
118
- }
119
- exports.createSourceEventStream = createSourceEventStream;
120
- async function executeSubscription(exeContext) {
121
- var _a;
122
- const { schema, fragments, operation, variableValues, rootValue } = exeContext;
123
- const rootType = schema.getSubscriptionType();
124
- if (rootType == null) {
125
- throw (0, utils_1.createGraphQLError)('Schema is not configured to execute subscription operation.', { nodes: operation });
126
- }
127
- const rootFields = (0, utils_1.collectFields)(schema, fragments, variableValues, rootType, operation.selectionSet);
128
- const [responseName, fieldNodes] = [...rootFields.entries()][0];
129
- const fieldDef = (0, execute_js_1.getFieldDef)(schema, rootType, fieldNodes[0]);
130
- if (!fieldDef) {
131
- const fieldName = fieldNodes[0].name.value;
132
- throw (0, utils_1.createGraphQLError)(`The subscription field "${fieldName}" is not defined.`, { nodes: fieldNodes });
133
- }
134
- const path = (0, utils_1.addPath)(undefined, responseName, rootType.name);
135
- const info = (0, execute_js_1.buildResolveInfo)(exeContext, fieldDef, fieldNodes, rootType, path);
136
- try {
137
- // Implements the "ResolveFieldEventStream" algorithm from GraphQL specification.
138
- // It differs from "ResolveFieldValue" due to providing a different `resolveFn`.
139
- // Build a JS object of arguments from the field.arguments AST, using the
140
- // variables scope to fulfill any variable references.
141
- const args = (0, utils_1.getArgumentValues)(fieldDef, fieldNodes[0], variableValues);
142
- // The resolve function's optional third argument is a context value that
143
- // is provided to every resolve function within an execution. It is commonly
144
- // used to represent an authenticated user, or request-specific caches.
145
- const contextValue = exeContext.contextValue;
146
- // Call the `subscribe()` resolver or the default resolver to produce an
147
- // AsyncIterable yielding raw payloads.
148
- const resolveFn = (_a = fieldDef.subscribe) !== null && _a !== void 0 ? _a : exeContext.subscribeFieldResolver;
149
- const eventStream = await resolveFn(rootValue, args, contextValue, info);
150
- if (eventStream instanceof Error) {
151
- throw eventStream;
152
- }
153
- return eventStream;
154
- }
155
- catch (error) {
156
- throw (0, graphql_1.locatedError)(error, fieldNodes, (0, utils_1.pathToArray)(path));
157
- }
158
- }
@@ -1,153 +0,0 @@
1
- import { GraphQLError, locatedError } from 'graphql';
2
- import { collectFields, mapAsyncIterator, inspect, isAsyncIterable, createGraphQLError, addPath, pathToArray, getArgumentValues, } from '@graphql-tools/utils';
3
- import { assertValidExecutionArguments, buildExecutionContext, buildResolveInfo, execute, getFieldDef, } from './execute.js';
4
- /**
5
- * Implements the "Subscribe" algorithm described in the GraphQL specification.
6
- *
7
- * Returns a Promise which resolves to either an AsyncIterator (if successful)
8
- * or an ExecutionResult (error). The promise will be rejected if the schema or
9
- * other arguments to this function are invalid, or if the resolved event stream
10
- * is not an async iterable.
11
- *
12
- * If the client-provided arguments to this function do not result in a
13
- * compliant subscription, a GraphQL Response (ExecutionResult) with
14
- * descriptive errors and no data will be returned.
15
- *
16
- * If the source stream could not be created due to faulty subscription
17
- * resolver logic or underlying systems, the promise will resolve to a single
18
- * ExecutionResult containing `errors` and no `data`.
19
- *
20
- * If the operation succeeded, the promise resolves to an AsyncIterator, which
21
- * yields a stream of ExecutionResults representing the response stream.
22
- *
23
- * Accepts either an object with named arguments, or individual arguments.
24
- */
25
- export async function subscribe(args) {
26
- // Temporary for v15 to v16 migration. Remove in v17
27
- console.assert(arguments.length < 2, 'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.');
28
- const { schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver, } = args;
29
- const resultOrStream = await createSourceEventStream(schema, document, rootValue, contextValue, variableValues, operationName, subscribeFieldResolver);
30
- if (!isAsyncIterable(resultOrStream)) {
31
- return resultOrStream;
32
- }
33
- // For each payload yielded from a subscription, map it over the normal
34
- // GraphQL `execute` function, with `payload` as the rootValue.
35
- // This implements the "MapSourceToResponseEvent" algorithm described in
36
- // the GraphQL specification. The `execute` function provides the
37
- // "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the
38
- // "ExecuteQuery" algorithm, for which `execute` is also used.
39
- const mapSourceToResponse = (payload) => execute({
40
- schema,
41
- document,
42
- rootValue: payload,
43
- contextValue,
44
- variableValues,
45
- operationName,
46
- fieldResolver,
47
- });
48
- // Map every source value to a ExecutionResult value as described above.
49
- return mapAsyncIterator(resultOrStream[Symbol.asyncIterator](), mapSourceToResponse);
50
- }
51
- /**
52
- * Implements the "CreateSourceEventStream" algorithm described in the
53
- * GraphQL specification, resolving the subscription source event stream.
54
- *
55
- * Returns a Promise which resolves to either an AsyncIterable (if successful)
56
- * or an ExecutionResult (error). The promise will be rejected if the schema or
57
- * other arguments to this function are invalid, or if the resolved event stream
58
- * is not an async iterable.
59
- *
60
- * If the client-provided arguments to this function do not result in a
61
- * compliant subscription, a GraphQL Response (ExecutionResult) with
62
- * descriptive errors and no data will be returned.
63
- *
64
- * If the the source stream could not be created due to faulty subscription
65
- * resolver logic or underlying systems, the promise will resolve to a single
66
- * ExecutionResult containing `errors` and no `data`.
67
- *
68
- * If the operation succeeded, the promise resolves to the AsyncIterable for the
69
- * event stream returned by the resolver.
70
- *
71
- * A Source Event Stream represents a sequence of events, each of which triggers
72
- * a GraphQL execution for that event.
73
- *
74
- * This may be useful when hosting the stateful subscription service in a
75
- * different process or machine than the stateless GraphQL execution engine,
76
- * or otherwise separating these two steps. For more on this, see the
77
- * "Supporting Subscriptions at Scale" information in the GraphQL specification.
78
- */
79
- export async function createSourceEventStream(schema, document, rootValue, contextValue, variableValues, operationName, subscribeFieldResolver) {
80
- // If arguments are missing or incorrectly typed, this is an internal
81
- // developer mistake which should throw an early error.
82
- assertValidExecutionArguments(schema, document, variableValues);
83
- // If a valid execution context cannot be created due to incorrect arguments,
84
- // a "Response" with only errors is returned.
85
- const exeContext = buildExecutionContext({
86
- schema,
87
- document,
88
- rootValue,
89
- contextValue,
90
- variableValues,
91
- operationName,
92
- subscribeFieldResolver,
93
- });
94
- // Return early errors if execution context failed.
95
- if (!('schema' in exeContext)) {
96
- return { errors: exeContext };
97
- }
98
- try {
99
- const eventStream = await executeSubscription(exeContext);
100
- // Assert field returned an event stream, otherwise yield an error.
101
- if (!isAsyncIterable(eventStream)) {
102
- throw new Error('Subscription field must return Async Iterable. ' + `Received: ${inspect(eventStream)}.`);
103
- }
104
- return eventStream;
105
- }
106
- catch (error) {
107
- // If it GraphQLError, report it as an ExecutionResult, containing only errors and no data.
108
- // Otherwise treat the error as a system-class error and re-throw it.
109
- if (error instanceof GraphQLError) {
110
- return { errors: [error] };
111
- }
112
- throw error;
113
- }
114
- }
115
- async function executeSubscription(exeContext) {
116
- var _a;
117
- const { schema, fragments, operation, variableValues, rootValue } = exeContext;
118
- const rootType = schema.getSubscriptionType();
119
- if (rootType == null) {
120
- throw createGraphQLError('Schema is not configured to execute subscription operation.', { nodes: operation });
121
- }
122
- const rootFields = collectFields(schema, fragments, variableValues, rootType, operation.selectionSet);
123
- const [responseName, fieldNodes] = [...rootFields.entries()][0];
124
- const fieldDef = getFieldDef(schema, rootType, fieldNodes[0]);
125
- if (!fieldDef) {
126
- const fieldName = fieldNodes[0].name.value;
127
- throw createGraphQLError(`The subscription field "${fieldName}" is not defined.`, { nodes: fieldNodes });
128
- }
129
- const path = addPath(undefined, responseName, rootType.name);
130
- const info = buildResolveInfo(exeContext, fieldDef, fieldNodes, rootType, path);
131
- try {
132
- // Implements the "ResolveFieldEventStream" algorithm from GraphQL specification.
133
- // It differs from "ResolveFieldValue" due to providing a different `resolveFn`.
134
- // Build a JS object of arguments from the field.arguments AST, using the
135
- // variables scope to fulfill any variable references.
136
- const args = getArgumentValues(fieldDef, fieldNodes[0], variableValues);
137
- // The resolve function's optional third argument is a context value that
138
- // is provided to every resolve function within an execution. It is commonly
139
- // used to represent an authenticated user, or request-specific caches.
140
- const contextValue = exeContext.contextValue;
141
- // Call the `subscribe()` resolver or the default resolver to produce an
142
- // AsyncIterable yielding raw payloads.
143
- const resolveFn = (_a = fieldDef.subscribe) !== null && _a !== void 0 ? _a : exeContext.subscribeFieldResolver;
144
- const eventStream = await resolveFn(rootValue, args, contextValue, info);
145
- if (eventStream instanceof Error) {
146
- throw eventStream;
147
- }
148
- return eventStream;
149
- }
150
- catch (error) {
151
- throw locatedError(error, fieldNodes, pathToArray(path));
152
- }
153
- }