subscribe.mjs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. import inspect from "../jsutils/inspect.mjs";
  2. import isAsyncIterable from "../jsutils/isAsyncIterable.mjs";
  3. import { addPath, pathToArray } from "../jsutils/Path.mjs";
  4. import { GraphQLError } from "../error/GraphQLError.mjs";
  5. import { locatedError } from "../error/locatedError.mjs";
  6. import { getArgumentValues } from "../execution/values.mjs";
  7. import { assertValidExecutionArguments, buildExecutionContext, buildResolveInfo, collectFields, execute, getFieldDef } 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. return new Promise(function (resolve) {
  103. // If a valid context cannot be created due to incorrect arguments,
  104. // this will throw an error.
  105. var exeContext = buildExecutionContext(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver);
  106. resolve( // Return early errors if execution context failed.
  107. Array.isArray(exeContext) ? {
  108. errors: exeContext
  109. } : executeSubscription(exeContext));
  110. }).catch(reportGraphQLError);
  111. }
  112. function executeSubscription(exeContext) {
  113. var schema = exeContext.schema,
  114. operation = exeContext.operation,
  115. variableValues = exeContext.variableValues,
  116. rootValue = exeContext.rootValue;
  117. var type = getOperationRootType(schema, operation);
  118. var fields = collectFields(exeContext, type, operation.selectionSet, Object.create(null), Object.create(null));
  119. var responseNames = Object.keys(fields);
  120. var responseName = responseNames[0];
  121. var fieldNodes = fields[responseName];
  122. var fieldNode = fieldNodes[0];
  123. var fieldName = fieldNode.name.value;
  124. var fieldDef = getFieldDef(schema, type, fieldName);
  125. if (!fieldDef) {
  126. throw new GraphQLError("The subscription field \"".concat(fieldName, "\" is not defined."), fieldNodes);
  127. }
  128. var path = addPath(undefined, responseName, type.name);
  129. var info = buildResolveInfo(exeContext, fieldDef, fieldNodes, type, path); // Coerce to Promise for easier error handling and consistent return type.
  130. return new Promise(function (resolveResult) {
  131. var _fieldDef$subscribe;
  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. var args = getArgumentValues(fieldDef, fieldNodes[0], variableValues); // The resolve function's optional third argument is a context value that
  137. // is provided to every resolve function within an execution. It is commonly
  138. // used to represent an authenticated user, or request-specific caches.
  139. var contextValue = exeContext.contextValue; // Call the `subscribe()` resolver or the default resolver to produce an
  140. // AsyncIterable yielding raw payloads.
  141. var resolveFn = (_fieldDef$subscribe = fieldDef.subscribe) !== null && _fieldDef$subscribe !== void 0 ? _fieldDef$subscribe : exeContext.fieldResolver;
  142. resolveResult(resolveFn(rootValue, args, contextValue, info));
  143. }).then(function (eventStream) {
  144. if (eventStream instanceof Error) {
  145. throw locatedError(eventStream, fieldNodes, pathToArray(path));
  146. } // Assert field returned an event stream, otherwise yield an error.
  147. if (!isAsyncIterable(eventStream)) {
  148. throw new Error('Subscription field must return Async Iterable. ' + "Received: ".concat(inspect(eventStream), "."));
  149. }
  150. return eventStream;
  151. }, function (error) {
  152. throw locatedError(error, fieldNodes, pathToArray(path));
  153. });
  154. }