subscribe.js.flow 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. // @flow strict
  2. import inspect from '../jsutils/inspect';
  3. import isAsyncIterable from '../jsutils/isAsyncIterable';
  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 type { ExecutionResult, ExecutionContext } from '../execution/execute';
  9. import { getArgumentValues } from '../execution/values';
  10. import {
  11. assertValidExecutionArguments,
  12. buildExecutionContext,
  13. buildResolveInfo,
  14. collectFields,
  15. execute,
  16. getFieldDef,
  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<AsyncGenerator<ExecutionResult, void, void> | 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: mixed): ExecutionResult {
  99. if (error instanceof GraphQLError) {
  100. return { errors: [error] };
  101. }
  102. throw error;
  103. }
  104. function subscribeImpl(
  105. args: SubscriptionArgs,
  106. ): Promise<AsyncGenerator<ExecutionResult, void, void> | 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. rootValue: 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,
  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. return new Promise((resolve) => {
  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. resolve(
  208. // Return early errors if execution context failed.
  209. Array.isArray(exeContext)
  210. ? { errors: exeContext }
  211. : executeSubscription(exeContext),
  212. );
  213. }).catch(reportGraphQLError);
  214. }
  215. function executeSubscription(
  216. exeContext: ExecutionContext,
  217. ): Promise<AsyncIterable<mixed>> {
  218. const { schema, operation, variableValues, rootValue } = exeContext;
  219. const type = getOperationRootType(schema, operation);
  220. const fields = collectFields(
  221. exeContext,
  222. type,
  223. operation.selectionSet,
  224. Object.create(null),
  225. Object.create(null),
  226. );
  227. const responseNames = Object.keys(fields);
  228. const responseName = responseNames[0];
  229. const fieldNodes = fields[responseName];
  230. const fieldNode = fieldNodes[0];
  231. const fieldName = fieldNode.name.value;
  232. const fieldDef = getFieldDef(schema, type, fieldName);
  233. if (!fieldDef) {
  234. throw new GraphQLError(
  235. `The subscription field "${fieldName}" is not defined.`,
  236. fieldNodes,
  237. );
  238. }
  239. const path = addPath(undefined, responseName, type.name);
  240. const info = buildResolveInfo(exeContext, fieldDef, fieldNodes, type, path);
  241. // Coerce to Promise for easier error handling and consistent return type.
  242. return new Promise((resolveResult) => {
  243. // Implements the "ResolveFieldEventStream" algorithm from GraphQL specification.
  244. // It differs from "ResolveFieldValue" due to providing a different `resolveFn`.
  245. // Build a JS object of arguments from the field.arguments AST, using the
  246. // variables scope to fulfill any variable references.
  247. const args = getArgumentValues(fieldDef, fieldNodes[0], variableValues);
  248. // The resolve function's optional third argument is a context value that
  249. // is provided to every resolve function within an execution. It is commonly
  250. // used to represent an authenticated user, or request-specific caches.
  251. const contextValue = exeContext.contextValue;
  252. // Call the `subscribe()` resolver or the default resolver to produce an
  253. // AsyncIterable yielding raw payloads.
  254. const resolveFn = fieldDef.subscribe ?? exeContext.fieldResolver;
  255. resolveResult(resolveFn(rootValue, args, contextValue, info));
  256. }).then(
  257. (eventStream) => {
  258. if (eventStream instanceof Error) {
  259. throw locatedError(eventStream, fieldNodes, pathToArray(path));
  260. }
  261. // Assert field returned an event stream, otherwise yield an error.
  262. if (!isAsyncIterable(eventStream)) {
  263. throw new Error(
  264. 'Subscription field must return Async Iterable. ' +
  265. `Received: ${inspect(eventStream)}.`,
  266. );
  267. }
  268. return eventStream;
  269. },
  270. (error) => {
  271. throw locatedError(error, fieldNodes, pathToArray(path));
  272. },
  273. );
  274. }