UNPKG

7.78 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.subscribe = subscribe;
7exports.createSourceEventStream = createSourceEventStream;
8
9var _iterall = require("iterall");
10
11var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
12
13var _Path = require("../jsutils/Path");
14
15var _GraphQLError = require("../error/GraphQLError");
16
17var _locatedError = require("../error/locatedError");
18
19var _execute = require("../execution/execute");
20
21var _getOperationRootType = require("../utilities/getOperationRootType");
22
23var _mapAsyncIterator = _interopRequireDefault(require("./mapAsyncIterator"));
24
25function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
26
27function subscribe(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver) {
28 /* eslint-enable no-redeclare */
29 // Extract arguments from object args if provided.
30 return arguments.length === 1 ? subscribeImpl(argsOrSchema) : subscribeImpl({
31 schema: argsOrSchema,
32 document: document,
33 rootValue: rootValue,
34 contextValue: contextValue,
35 variableValues: variableValues,
36 operationName: operationName,
37 fieldResolver: fieldResolver,
38 subscribeFieldResolver: subscribeFieldResolver
39 });
40}
41/**
42 * This function checks if the error is a GraphQLError. If it is, report it as
43 * an ExecutionResult, containing only errors and no data. Otherwise treat the
44 * error as a system-class error and re-throw it.
45 */
46
47
48function reportGraphQLError(error) {
49 if (error instanceof _GraphQLError.GraphQLError) {
50 return {
51 errors: [error]
52 };
53 }
54
55 throw error;
56}
57
58function subscribeImpl(args) {
59 var schema = args.schema,
60 document = args.document,
61 rootValue = args.rootValue,
62 contextValue = args.contextValue,
63 variableValues = args.variableValues,
64 operationName = args.operationName,
65 fieldResolver = args.fieldResolver,
66 subscribeFieldResolver = args.subscribeFieldResolver;
67 var sourcePromise = createSourceEventStream(schema, document, rootValue, contextValue, variableValues, operationName, subscribeFieldResolver); // For each payload yielded from a subscription, map it over the normal
68 // GraphQL `execute` function, with `payload` as the rootValue.
69 // This implements the "MapSourceToResponseEvent" algorithm described in
70 // the GraphQL specification. The `execute` function provides the
71 // "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the
72 // "ExecuteQuery" algorithm, for which `execute` is also used.
73
74 var mapSourceToResponse = function mapSourceToResponse(payload) {
75 return (0, _execute.execute)(schema, document, payload, contextValue, variableValues, operationName, fieldResolver);
76 }; // Resolve the Source Stream, then map every source value to a
77 // ExecutionResult value as described above.
78
79
80 return sourcePromise.then(function (resultOrStream) {
81 return (// Note: Flow can't refine isAsyncIterable, so explicit casts are used.
82 (0, _iterall.isAsyncIterable)(resultOrStream) ? (0, _mapAsyncIterator.default)(resultOrStream, mapSourceToResponse, reportGraphQLError) : resultOrStream
83 );
84 });
85}
86/**
87 * Implements the "CreateSourceEventStream" algorithm described in the
88 * GraphQL specification, resolving the subscription source event stream.
89 *
90 * Returns a Promise which resolves to either an AsyncIterable (if successful)
91 * or an ExecutionResult (error). The promise will be rejected if the schema or
92 * other arguments to this function are invalid, or if the resolved event stream
93 * is not an async iterable.
94 *
95 * If the client-provided arguments to this function do not result in a
96 * compliant subscription, a GraphQL Response (ExecutionResult) with
97 * descriptive errors and no data will be returned.
98 *
99 * If the the source stream could not be created due to faulty subscription
100 * resolver logic or underlying systems, the promise will resolve to a single
101 * ExecutionResult containing `errors` and no `data`.
102 *
103 * If the operation succeeded, the promise resolves to the AsyncIterable for the
104 * event stream returned by the resolver.
105 *
106 * A Source Event Stream represents a sequence of events, each of which triggers
107 * a GraphQL execution for that event.
108 *
109 * This may be useful when hosting the stateful subscription service in a
110 * different process or machine than the stateless GraphQL execution engine,
111 * or otherwise separating these two steps. For more on this, see the
112 * "Supporting Subscriptions at Scale" information in the GraphQL specification.
113 */
114
115
116function createSourceEventStream(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver) {
117 // If arguments are missing or incorrectly typed, this is an internal
118 // developer mistake which should throw an early error.
119 (0, _execute.assertValidExecutionArguments)(schema, document, variableValues);
120
121 try {
122 // If a valid context cannot be created due to incorrect arguments,
123 // this will throw an error.
124 var exeContext = (0, _execute.buildExecutionContext)(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver); // Return early errors if execution context failed.
125
126 if (Array.isArray(exeContext)) {
127 return Promise.resolve({
128 errors: exeContext
129 });
130 }
131
132 var type = (0, _getOperationRootType.getOperationRootType)(schema, exeContext.operation);
133 var fields = (0, _execute.collectFields)(exeContext, type, exeContext.operation.selectionSet, Object.create(null), Object.create(null));
134 var responseNames = Object.keys(fields);
135 var responseName = responseNames[0];
136 var fieldNodes = fields[responseName];
137 var fieldNode = fieldNodes[0];
138 var fieldName = fieldNode.name.value;
139 var fieldDef = (0, _execute.getFieldDef)(schema, type, fieldName);
140
141 if (!fieldDef) {
142 throw new _GraphQLError.GraphQLError("The subscription field \"".concat(fieldName, "\" is not defined."), fieldNodes);
143 } // Call the `subscribe()` resolver or the default resolver to produce an
144 // AsyncIterable yielding raw payloads.
145
146
147 var resolveFn = fieldDef.subscribe || exeContext.fieldResolver;
148 var path = (0, _Path.addPath)(undefined, responseName);
149 var info = (0, _execute.buildResolveInfo)(exeContext, fieldDef, fieldNodes, type, path); // resolveFieldValueOrError implements the "ResolveFieldEventStream"
150 // algorithm from GraphQL specification. It differs from
151 // "ResolveFieldValue" due to providing a different `resolveFn`.
152
153 var result = (0, _execute.resolveFieldValueOrError)(exeContext, fieldDef, fieldNodes, resolveFn, rootValue, info); // Coerce to Promise for easier error handling and consistent return type.
154
155 return Promise.resolve(result).then(function (eventStream) {
156 // If eventStream is an Error, rethrow a located error.
157 if (eventStream instanceof Error) {
158 return {
159 errors: [(0, _locatedError.locatedError)(eventStream, fieldNodes, (0, _Path.pathToArray)(path))]
160 };
161 } // Assert field returned an event stream, otherwise yield an error.
162
163
164 if ((0, _iterall.isAsyncIterable)(eventStream)) {
165 // Note: isAsyncIterable above ensures this will be correct.
166 return eventStream;
167 }
168
169 throw new Error('Subscription field must return Async Iterable. Received: ' + (0, _inspect.default)(eventStream));
170 });
171 } catch (error) {
172 // As with reportGraphQLError above, if the error is a GraphQLError, report
173 // it as an ExecutionResult; otherwise treat it as a system-class error and
174 // re-throw it.
175 return error instanceof _GraphQLError.GraphQLError ? Promise.resolve({
176 errors: [error]
177 }) : Promise.reject(error);
178 }
179}