UNPKG

graphql-yoga

Version:
522 lines (521 loc) • 24.2 kB
import { parse, specifiedRules, validate } from 'graphql'; import { envelop, isAsyncIterable, useEngine, useExtendContext, useMaskedErrors, } from '@envelop/core'; import { chain, getInstrumented } from '@envelop/instrumentation'; import { normalizedExecutor } from '@graphql-tools/executor'; import * as defaultFetchAPI from '@whatwg-node/fetch'; import { fakePromise, handleMaybePromise, iterateAsync, iterateAsyncVoid, mapAsyncIterator, unfakePromise, } from '@whatwg-node/promise-helpers'; import { createServerAdapter, useCORS } from '@whatwg-node/server'; import { handleError, isAbortError } from './error.js'; import { createLoggerFromLogging } from './logger.js'; import { useAllowedRequestHeaders, useAllowedResponseHeaders } from './plugins/allowed-headers.js'; import { isGETRequest, parseGETRequest } from './plugins/request-parser/get.js'; import { isPOSTFormUrlEncodedRequest, parsePOSTFormUrlEncodedRequest, } from './plugins/request-parser/post-form-url-encoded.js'; import { isPOSTGraphQLStringRequest, parsePOSTGraphQLStringRequest, } from './plugins/request-parser/post-graphql-string.js'; import { isPOSTJsonRequest, parsePOSTJsonRequest } from './plugins/request-parser/post-json.js'; import { isPOSTMultipartRequest, parsePOSTMultipartRequest, } from './plugins/request-parser/post-multipart.js'; import { useCheckGraphQLQueryParams } from './plugins/request-validation/use-check-graphql-query-params.js'; import { useCheckMethodForGraphQL } from './plugins/request-validation/use-check-method-for-graphql.js'; import { useHTTPValidationError } from './plugins/request-validation/use-http-validation-error.js'; import { useLimitBatching } from './plugins/request-validation/use-limit-batching.js'; import { useLimitRequestBodySize } from './plugins/request-validation/use-limit-request-body-size.js'; import { usePreventMutationViaGET } from './plugins/request-validation/use-prevent-mutation-via-get.js'; import { useConfigInServerContext } from './plugins/use-config-in-server-context.js'; import { useGraphiQL } from './plugins/use-graphiql.js'; import { useHealthCheck } from './plugins/use-health-check.js'; import { useParserAndValidationCache } from './plugins/use-parser-and-validation-cache.js'; import { getRequestIdHeaderName, useRequestId } from './plugins/use-request-id.js'; import { useRequestParser } from './plugins/use-request-parser.js'; import { useResultProcessors } from './plugins/use-result-processor.js'; import { useSchema } from './plugins/use-schema.js'; import { useUnhandledRoute } from './plugins/use-unhandled-route.js'; import { processRequest as processGraphQLParams, processResult } from './process-request.js'; import { isResponse } from './utils/is-response.js'; import { maskError } from './utils/mask-error.js'; /** * Counts the GraphQL errors carried by a result, for the per-request summary log. * Returns `undefined` for a streaming result (subscription/SSE), whose errors (if any) surface * progressively while the response streams rather than being known up front. */ function countErrors(result) { if (isAsyncIterable(result)) { return undefined; } const results = Array.isArray(result) ? result : [result]; return results.reduce((count, result) => count + (result.errors?.length ?? 0), 0); } /** * Base class that can be extended to create a GraphQL server with any HTTP server framework. * @internal */ export class YogaServer { /** * Instance of envelop */ getEnveloped; log; fetchAPI; plugins; instrumentation; onRequestParseHooks; onParamsHooks; onExecutionResultHooks; onResultProcessHooks; maskedErrorsOpts; id; /** * Operation type resolved for a given request, read back for the per-request summary log. */ operationTypeByContext = new WeakMap(); // @ts-expect-error - This is set by `this.graphqlEndpoint` setter in the constructor, but TypeScript doesn't recognize it. _graphqlEndpoint; _graphqlEndpointURLPattern; version = '6.0.1'; constructor(options) { this.id = options?.id ?? 'yoga'; this.fetchAPI = { ...defaultFetchAPI, }; if (options?.fetchAPI) { for (const key in options.fetchAPI) { if (options.fetchAPI[key]) { this.fetchAPI[key] = options.fetchAPI[key]; } } } this.log = createLoggerFromLogging(options?.logging); const configContext = { log: this.log }; const maskErrorFn = (typeof options?.maskedErrors === 'object' && options.maskedErrors.maskError) || maskError; const maskedErrorSet = new WeakSet(); this.maskedErrorsOpts = options?.maskedErrors === false ? null : { errorMessage: 'Unexpected error.', ...(typeof options?.maskedErrors === 'object' ? options.maskedErrors : {}), // `context` is the request's context, to correlate this error with the request that // caused it (and give the user's own `maskError`, if any, more to work with than // just a logger). Passed explicitly by `handleError` (error.ts) for the HTTP path; // for subscription/streaming errors, `useMaskedErrors` calls this via the adapter // below, which gets it from the GraphQL context it's given. maskError: (error, message, _isDev, context) => { if (maskedErrorSet.has(error)) { return error; } const newError = maskErrorFn(error, message, this.maskedErrorsOpts?.isDev, context); if (newError !== error) { (context?.log ?? this.log).error({ err: error }); } maskedErrorSet.add(newError); return newError; }, }; const maskedErrors = this.maskedErrorsOpts == null ? null : this.maskedErrorsOpts; let batchingLimit = 0; if (options?.batching) { if (typeof options.batching === 'boolean') { batchingLimit = 10; } else { batchingLimit = options.batching.limit ?? 10; } } this.graphqlEndpoint = options?.graphqlEndpoint || '/graphql'; const requestIdEnabled = options?.requestId !== false; const requestIdOpts = typeof options?.requestId === 'object' ? options.requestId : undefined; const requestIdHeaderName = getRequestIdHeaderName(requestIdOpts); this.plugins = [ useEngine({ parse, validate, execute: normalizedExecutor, subscribe: normalizedExecutor, specifiedRules, }), // Make the config (and therefore the logger) available in the server context of every // request. Registered first so that everything after it can rely on `log` being there. useConfigInServerContext({ configContext }), // Use the schema provided by the user !!options?.schema && useSchema(options.schema), options?.allowedHeaders?.request != null && useAllowedRequestHeaders(options.allowedHeaders.request), // Scope the logger of each request to its request id. Registered after the request headers // have been filtered, so that a request id is only taken from an allowed header, but before // the plugins that log while short-circuiting a request (health checks, GraphiQL). requestIdEnabled && useRequestId(requestIdOpts), options?.context != null && useExtendContext(initialContext => { if (options?.context) { if (typeof options.context === 'function') { return options.context(initialContext); } return options.context; } return {}; }), // Middlewares before processing the incoming HTTP request useHealthCheck({ id: this.id, endpoint: options?.healthCheckEndpoint, }), options?.cors !== false && useCORS(options?.cors), options?.graphiql !== false && useGraphiQL({ getGraphQLEndpoint: () => this._graphqlEndpoint, getGraphQLEndpointURLPattern: () => this.getUrlPatternForGraphQLEndpoint(), options: options?.graphiql, render: options?.renderGraphiQL, }), // Middlewares before the GraphQL execution useRequestParser({ match: isGETRequest, parse: parseGETRequest, }), useRequestParser({ match: isPOSTJsonRequest, parse: parsePOSTJsonRequest, }), options?.multipart !== false && useRequestParser({ match: isPOSTMultipartRequest, parse: parsePOSTMultipartRequest, }), useRequestParser({ match: isPOSTGraphQLStringRequest, parse: parsePOSTGraphQLStringRequest, }), useRequestParser({ match: isPOSTFormUrlEncodedRequest, parse: parsePOSTFormUrlEncodedRequest, }), // Middlewares after the GraphQL execution useResultProcessors(), ...(options?.plugins ?? []), // Must run after the request parsers above (including any registered by user plugins) // so it wraps whichever parser ends up selected. options?.maxRequestBodySize !== false && useLimitRequestBodySize(options?.maxRequestBodySize ?? 25_000_000), options?.parserAndValidationCache !== false && useParserAndValidationCache(!options?.parserAndValidationCache || options?.parserAndValidationCache === true ? {} : options?.parserAndValidationCache), useLimitBatching(batchingLimit), useCheckGraphQLQueryParams(options?.extraParamNames), useUnhandledRoute({ getGraphQLEndpoint: () => this.graphqlEndpoint, getGraphQLEndpointURLPattern: () => this.getUrlPatternForGraphQLEndpoint(), showLandingPage: options?.landingPage !== false, landingPageRenderer: typeof options?.landingPage === 'function' ? options.landingPage : undefined, }), // We check the method after user-land plugins because the plugin might support more methods (like graphql-sse). useCheckMethodForGraphQL(), // We make sure that the user doesn't send a mutation with GET usePreventMutationViaGET(), // Always throw AbortError instead of masking it. maskedErrors !== null && { onSubscribe: () => ({ onSubscribeError({ error }) { if (isAbortError(error)) { throw error; } }, }), }, maskedErrors !== null && useMaskedErrors({ errorMessage: maskedErrors.errorMessage, // `useMaskedErrors` gives us the GraphQL context here; forward it to the real // `maskError` (defined above) as an explicit argument. maskError: (error, message, context) => maskedErrors.maskError(error, message, undefined, context), }), options?.allowedHeaders?.response != null && // Registered last (after CORS and user plugins) so it sees every header anything else // added. useAllowedResponseHeaders(requestIdEnabled ? [...options.allowedHeaders.response, requestIdHeaderName] : options.allowedHeaders.response), // We handle validation errors at the end useHTTPValidationError(), ]; this.getEnveloped = envelop({ plugins: this.plugins, }); this.plugins = this.getEnveloped._plugins; this.onRequestParseHooks = []; this.onParamsHooks = []; this.onExecutionResultHooks = []; this.onResultProcessHooks = []; for (const plugin of this.plugins) { if (plugin) { if (plugin.onYogaInit) { plugin.onYogaInit({ yoga: this, }); } if (plugin.onRequestParse) { this.onRequestParseHooks.push(plugin.onRequestParse); } if (plugin.onParams) { this.onParamsHooks.push(plugin.onParams); } if (plugin.onExecutionResult) { this.onExecutionResultHooks.push(plugin.onExecutionResult); } if (plugin.onResultProcess) { this.onResultProcessHooks.push(plugin.onResultProcess); } if (plugin.instrumentation) { this.instrumentation = this.instrumentation ? chain(this.instrumentation, plugin.instrumentation) : plugin.instrumentation; } } } } get graphqlEndpoint() { return this._graphqlEndpoint; } set graphqlEndpoint(endpoint) { this._graphqlEndpoint = endpoint; this._graphqlEndpointURLPattern = undefined; } getUrlPatternForGraphQLEndpoint() { this._graphqlEndpointURLPattern ??= new this.fetchAPI.URLPattern({ pathname: this._graphqlEndpoint, }); return this._graphqlEndpointURLPattern; } handleParams = ({ request, context, params }) => { const additionalContext = context['request'] === request ? { params, } : { request, params, }; Object.assign(context, additionalContext); const enveloped = this.getEnveloped(context); const log = context.log; log.debug(() => ({ path: new this.fetchAPI.URL(request.url, 'http://localhost').pathname, operationName: params.operationName, variablesCount: params.variables ? Object.keys(params.variables).length : 0, }), 'Processing GraphQL Parameters'); return handleMaybePromise(() => handleMaybePromise(() => processGraphQLParams({ params, enveloped, request, log, onOperationType: operationType => this.operationTypeByContext.set(context, operationType), }), result => { log.debug(`Processing GraphQL Parameters done.`); return result; }, error => { const errors = handleError(error, this.maskedErrorsOpts, context); return { errors, }; }), result => { if (isAsyncIterable(result)) { result = mapAsyncIterator(result, v => v, (error) => { if (error.name === 'AbortError') { log.debug(`Request aborted`); throw error; } const errors = handleError(error, this.maskedErrorsOpts, context); return { errors, }; }); } return result; }); }; getResultForParams = ({ params, request, }, context, fetchAPI = this.fetchAPI) => { let result; let paramsHandler = this.handleParams; return handleMaybePromise(() => iterateAsync(this.onParamsHooks, onParamsHook => onParamsHook({ params, request, setParams(newParams) { params = newParams; }, paramsHandler, setParamsHandler(newHandler) { paramsHandler = newHandler; }, setResult(newResult) { result = newResult; }, fetchAPI, context, })), () => handleMaybePromise(() => result || paramsHandler({ request, params, context: context, }), result => handleMaybePromise(() => iterateAsync(this.onExecutionResultHooks, onExecutionResult => onExecutionResult({ result, setResult(newResult) { result = newResult; }, request, context: context, })), () => result))); }; parseRequest = (request, serverContext, fetchAPI = this.fetchAPI) => { let url = new Proxy({}, { get: (_target, prop, _receiver) => { url = new fetchAPI.URL(request.url, 'http://localhost'); return Reflect.get(url, prop, url); }, }); let requestParser; let response; const onRequestParseDoneList = []; return handleMaybePromise(() => iterateAsync(this.onRequestParseHooks, (onRequestParse, endEarly) => handleMaybePromise(() => onRequestParse({ request, url, requestParser, serverContext, setRequestParser(parser) { requestParser = parser; }, // Short-circuit the request parsing if a response is sent in `onRequestParse` endResponse(res) { response = res; endEarly(); }, fetchAPI, }), requestParseHookResult => requestParseHookResult?.onRequestParseDone), onRequestParseDoneList), () => { if (response) { return { response }; } serverContext.log.debug(`Parsing request to extract GraphQL parameters`); if (!requestParser) { return { response: new fetchAPI.Response(null, { status: 415, statusText: 'Unsupported Media Type', }), }; } return handleMaybePromise(() => requestParser(request), requestParserFnResult => { if (isResponse(requestParserFnResult)) { return { response: requestParserFnResult, }; } let requestParserResult = requestParserFnResult; return handleMaybePromise(() => iterateAsyncVoid(onRequestParseDoneList, onRequestParseDone => onRequestParseDone({ requestParserResult, setRequestParserResult(newParams) { requestParserResult = newParams; }, })), () => ({ requestParserResult, })); }); }); }; handle = (request, adapterServerContext, fetchAPI = this.fetchAPI) => { // `useConfigInServerContext` and `useRequestId` have put the request-scoped logger in the // server context by now, so everything logged for this request is correlated by its id const serverContext = adapterServerContext; const log = serverContext.log; const start = performance.now(); const instrumented = this.instrumentation && getInstrumented({ request }); const parseRequest = this.instrumentation?.requestParse ? instrumented.asyncFn(this.instrumentation?.requestParse, this.parseRequest) : this.parseRequest; let requestParserResult; let errorCount; return unfakePromise(fakePromise() .then(() => parseRequest(request, serverContext, fetchAPI)) .then(parseResult => { requestParserResult = parseResult.requestParserResult; const { response, requestParserResult: parserResult } = parseResult; if (response) { return response; } const getResultForParams = this.instrumentation?.operation ? (payload, context, fetchAPI) => { const instrumented = getInstrumented({ context, request: payload.request }); const tracedHandler = instrumented.asyncFn(this.instrumentation?.operation, this.getResultForParams); return tracedHandler(payload, context, fetchAPI); } : this.getResultForParams; return handleMaybePromise(() => (Array.isArray(parserResult) ? Promise.all(parserResult.map(params => { const context = Object.create(serverContext); return (fakePromise() .then(() => getResultForParams({ params, request }, context, fetchAPI)) // eslint-disable-next-line promise/no-nesting .catch(error => { const errors = handleError(error, this.maskedErrorsOpts, context); return { errors, }; })); })) : getResultForParams({ params: parserResult, request, }, serverContext, fetchAPI)), result => { errorCount = countErrors(result); const tracedProcessResult = this.instrumentation?.resultProcess ? instrumented.asyncFn(this.instrumentation.resultProcess, processResult) : processResult; return tracedProcessResult({ request, result, fetchAPI, onResultProcessHooks: this.onResultProcessHooks, serverContext, }); }); }) .catch(error => { const errors = handleError(error, this.maskedErrorsOpts, serverContext); errorCount = errors.length; const result = { errors, }; return processResult({ request, result, fetchAPI, onResultProcessHooks: this.onResultProcessHooks, serverContext, }); }) .then(response => { log.info(() => ({ method: request.method, path: new fetchAPI.URL(request.url, 'http://localhost').pathname, operationName: Array.isArray(requestParserResult) ? undefined : requestParserResult?.operationName, operationType: Array.isArray(requestParserResult) ? undefined : requestParserResult && this.operationTypeByContext.get(serverContext), batchedOperations: Array.isArray(requestParserResult) ? requestParserResult.length : undefined, status: response.status, errorCount, durationMs: Math.round(performance.now() - start), }), 'Request processed'); return response; })); }; } export function createYoga(options) { const server = new YogaServer(options); return createServerAdapter(server, { fetchAPI: server.fetchAPI, // the plugins expect `log` in the server context, which `useConfigInServerContext` puts there first plugins: server['plugins'], disposeOnProcessTerminate: options.disposeOnProcessTerminate, }); }