subscribe.js.flow 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. // @flow strict
  2. import { isAsyncIterable } from 'iterall';
  3. import inspect from '../jsutils/inspect';
  4. import { addPath, pathToArray } from '../jsutils/Path';
  5. import { GraphQLError } from '../error/GraphQLError';
  6. import { locatedError } from '../error/locatedError';
  7. import { type DocumentNode } from '../language/ast';
  8. import {
  9. type ExecutionResult,
  10. assertValidExecutionArguments,
  11. buildExecutionContext,
  12. buildResolveInfo,
  13. collectFields,
  14. execute,
  15. getFieldDef,
  16. resolveFieldValueOrError,
  17. } from '../execution/execute';
  18. import { type GraphQLSchema } from '../type/schema';
  19. import { type GraphQLFieldResolver } from '../type/definition';
  20. import { getOperationRootType } from '../utilities/getOperationRootType';
  21. import mapAsyncIterator from './mapAsyncIterator';
  22. export type SubscriptionArgs = {|
  23. schema: GraphQLSchema,
  24. document: DocumentNode,
  25. rootValue?: mixed,
  26. contextValue?: mixed,
  27. variableValues?: ?{ +[variable: string]: mixed, ... },
  28. operationName?: ?string,
  29. fieldResolver?: ?GraphQLFieldResolver<any, any>,
  30. subscribeFieldResolver?: ?GraphQLFieldResolver<any, any>,
  31. |};
  32. /**
  33. * Implements the "Subscribe" algorithm described in the GraphQL specification.
  34. *
  35. * Returns a Promise which resolves to either an AsyncIterator (if successful)
  36. * or an ExecutionResult (error). The promise will be rejected if the schema or
  37. * other arguments to this function are invalid, or if the resolved event stream
  38. * is not an async iterable.
  39. *
  40. * If the client-provided arguments to this function do not result in a
  41. * compliant subscription, a GraphQL Response (ExecutionResult) with
  42. * descriptive errors and no data will be returned.
  43. *
  44. * If the source stream could not be created due to faulty subscription
  45. * resolver logic or underlying systems, the promise will resolve to a single
  46. * ExecutionResult containing `errors` and no `data`.
  47. *
  48. * If the operation succeeded, the promise resolves to an AsyncIterator, which
  49. * yields a stream of ExecutionResults representing the response stream.
  50. *
  51. * Accepts either an object with named arguments, or individual arguments.
  52. */
  53. declare function subscribe(
  54. SubscriptionArgs,
  55. ..._: []
  56. ): Promise<AsyncIterator<ExecutionResult> | ExecutionResult>;
  57. /* eslint-disable no-redeclare */
  58. declare function subscribe(
  59. schema: GraphQLSchema,
  60. document: DocumentNode,
  61. rootValue?: mixed,
  62. contextValue?: mixed,
  63. variableValues?: ?{ +[variable: string]: mixed, ... },
  64. operationName?: ?string,
  65. fieldResolver?: ?GraphQLFieldResolver<any, any>,
  66. subscribeFieldResolver?: ?GraphQLFieldResolver<any, any>,
  67. ): Promise<AsyncIterator<ExecutionResult> | ExecutionResult>;
  68. export function subscribe(
  69. argsOrSchema,
  70. document,
  71. rootValue,
  72. contextValue,
  73. variableValues,
  74. operationName,
  75. fieldResolver,
  76. subscribeFieldResolver,
  77. ) {
  78. /* eslint-enable no-redeclare */
  79. // Extract arguments from object args if provided.
  80. return arguments.length === 1
  81. ? subscribeImpl(argsOrSchema)
  82. : subscribeImpl({
  83. schema: argsOrSchema,
  84. document,
  85. rootValue,
  86. contextValue,
  87. variableValues,
  88. operationName,
  89. fieldResolver,
  90. subscribeFieldResolver,
  91. });
  92. }
  93. /**
  94. * This function checks if the error is a GraphQLError. If it is, report it as
  95. * an ExecutionResult, containing only errors and no data. Otherwise treat the
  96. * error as a system-class error and re-throw it.
  97. */
  98. function reportGraphQLError(error) {
  99. if (error instanceof GraphQLError) {
  100. return { errors: [error] };
  101. }
  102. throw error;
  103. }
  104. function subscribeImpl(
  105. args: SubscriptionArgs,
  106. ): Promise<AsyncIterator<ExecutionResult> | ExecutionResult> {
  107. const {
  108. schema,
  109. document,
  110. rootValue,
  111. contextValue,
  112. variableValues,
  113. operationName,
  114. fieldResolver,
  115. subscribeFieldResolver,
  116. } = args;
  117. const sourcePromise = createSourceEventStream(
  118. schema,
  119. document,
  120. rootValue,
  121. contextValue,
  122. variableValues,
  123. operationName,
  124. subscribeFieldResolver,
  125. );
  126. // For each payload yielded from a subscription, map it over the normal
  127. // GraphQL `execute` function, with `payload` as the rootValue.
  128. // This implements the "MapSourceToResponseEvent" algorithm described in
  129. // the GraphQL specification. The `execute` function provides the
  130. // "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the
  131. // "ExecuteQuery" algorithm, for which `execute` is also used.
  132. const mapSourceToResponse = payload =>
  133. execute(
  134. schema,
  135. document,
  136. payload,
  137. contextValue,
  138. variableValues,
  139. operationName,
  140. fieldResolver,
  141. );
  142. // Resolve the Source Stream, then map every source value to a
  143. // ExecutionResult value as described above.
  144. return sourcePromise.then(resultOrStream =>
  145. // Note: Flow can't refine isAsyncIterable, so explicit casts are used.
  146. isAsyncIterable(resultOrStream)
  147. ? mapAsyncIterator(
  148. ((resultOrStream: any): AsyncIterable<mixed>),
  149. mapSourceToResponse,
  150. reportGraphQLError,
  151. )
  152. : ((resultOrStream: any): ExecutionResult),
  153. );
  154. }
  155. /**
  156. * Implements the "CreateSourceEventStream" algorithm described in the
  157. * GraphQL specification, resolving the subscription source event stream.
  158. *
  159. * Returns a Promise which resolves to either an AsyncIterable (if successful)
  160. * or an ExecutionResult (error). The promise will be rejected if the schema or
  161. * other arguments to this function are invalid, or if the resolved event stream
  162. * is not an async iterable.
  163. *
  164. * If the client-provided arguments to this function do not result in a
  165. * compliant subscription, a GraphQL Response (ExecutionResult) with
  166. * descriptive errors and no data will be returned.
  167. *
  168. * If the the source stream could not be created due to faulty subscription
  169. * resolver logic or underlying systems, the promise will resolve to a single
  170. * ExecutionResult containing `errors` and no `data`.
  171. *
  172. * If the operation succeeded, the promise resolves to the AsyncIterable for the
  173. * event stream returned by the resolver.
  174. *
  175. * A Source Event Stream represents a sequence of events, each of which triggers
  176. * a GraphQL execution for that event.
  177. *
  178. * This may be useful when hosting the stateful subscription service in a
  179. * different process or machine than the stateless GraphQL execution engine,
  180. * or otherwise separating these two steps. For more on this, see the
  181. * "Supporting Subscriptions at Scale" information in the GraphQL specification.
  182. */
  183. export function createSourceEventStream(
  184. schema: GraphQLSchema,
  185. document: DocumentNode,
  186. rootValue?: mixed,
  187. contextValue?: mixed,
  188. variableValues?: ?{ +[variable: string]: mixed, ... },
  189. operationName?: ?string,
  190. fieldResolver?: ?GraphQLFieldResolver<any, any>,
  191. ): Promise<AsyncIterable<mixed> | ExecutionResult> {
  192. // If arguments are missing or incorrectly typed, this is an internal
  193. // developer mistake which should throw an early error.
  194. assertValidExecutionArguments(schema, document, variableValues);
  195. try {
  196. // If a valid context cannot be created due to incorrect arguments,
  197. // this will throw an error.
  198. const exeContext = buildExecutionContext(
  199. schema,
  200. document,
  201. rootValue,
  202. contextValue,
  203. variableValues,
  204. operationName,
  205. fieldResolver,
  206. );
  207. // Return early errors if execution context failed.
  208. if (Array.isArray(exeContext)) {
  209. return Promise.resolve({ errors: exeContext });
  210. }
  211. const type = getOperationRootType(schema, exeContext.operation);
  212. const fields = collectFields(
  213. exeContext,
  214. type,
  215. exeContext.operation.selectionSet,
  216. Object.create(null),
  217. Object.create(null),
  218. );
  219. const responseNames = Object.keys(fields);
  220. const responseName = responseNames[0];
  221. const fieldNodes = fields[responseName];
  222. const fieldNode = fieldNodes[0];
  223. const fieldName = fieldNode.name.value;
  224. const fieldDef = getFieldDef(schema, type, fieldName);
  225. if (!fieldDef) {
  226. throw new GraphQLError(
  227. `The subscription field "${fieldName}" is not defined.`,
  228. fieldNodes,
  229. );
  230. }
  231. // Call the `subscribe()` resolver or the default resolver to produce an
  232. // AsyncIterable yielding raw payloads.
  233. const resolveFn = fieldDef.subscribe || exeContext.fieldResolver;
  234. const path = addPath(undefined, responseName);
  235. const info = buildResolveInfo(exeContext, fieldDef, fieldNodes, type, path);
  236. // resolveFieldValueOrError implements the "ResolveFieldEventStream"
  237. // algorithm from GraphQL specification. It differs from
  238. // "ResolveFieldValue" due to providing a different `resolveFn`.
  239. const result = resolveFieldValueOrError(
  240. exeContext,
  241. fieldDef,
  242. fieldNodes,
  243. resolveFn,
  244. rootValue,
  245. info,
  246. );
  247. // Coerce to Promise for easier error handling and consistent return type.
  248. return Promise.resolve(result).then(eventStream => {
  249. // If eventStream is an Error, rethrow a located error.
  250. if (eventStream instanceof Error) {
  251. return {
  252. errors: [locatedError(eventStream, fieldNodes, pathToArray(path))],
  253. };
  254. }
  255. // Assert field returned an event stream, otherwise yield an error.
  256. if (isAsyncIterable(eventStream)) {
  257. // Note: isAsyncIterable above ensures this will be correct.
  258. return ((eventStream: any): AsyncIterable<mixed>);
  259. }
  260. throw new Error(
  261. 'Subscription field must return Async Iterable. Received: ' +
  262. inspect(eventStream),
  263. );
  264. });
  265. } catch (error) {
  266. // As with reportGraphQLError above, if the error is a GraphQLError, report
  267. // it as an ExecutionResult; otherwise treat it as a system-class error and
  268. // re-throw it.
  269. return error instanceof GraphQLError
  270. ? Promise.resolve({ errors: [error] })
  271. : Promise.reject(error);
  272. }
  273. }