subscribe.js 7.6 KB

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