subscribe.js 8.6 KB

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