subscribe.mjs 8.3 KB

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