subscribe.mjs 7.2 KB

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