graphql-yoga

  • Version 5.18.0
  • Published
  • 293 kB
  • 12 dependencies
  • MIT license

Install

npm i graphql-yoga
yarn add graphql-yoga
pnpm add graphql-yoga

Overview

<div align="center"><img src="https://raw.githubusercontent.com/graphql-hive/graphql-yoga/refs/heads/main/website/public/cover.png" width="720" /></div>

Index

Variables

variable createLRUCache

const createLRUCache: <T extends {}>({
max,
ttl,
}?: _LRUCacheOptions) => LRU<string, T, unknown>;
  • Deprecated

    In the next major, createLRUCache will be renamed to _createLRUCache, and the current createLRUCache will be removed.

variable maskError

const maskError: MaskError;

    Functions

    function createSchema

    createSchema: <TContext = {}>(
    opts: IExecutableSchemaDefinition<TContext & YogaInitialContext>
    ) => GraphQLSchemaWithContext<TContext & YogaInitialContext>;

      function createYoga

      createYoga: <
      TServerContext extends Record<string, any> = {},
      TUserContext extends Record<string, any> = {}
      >(
      options: YogaServerOptions<TServerContext, TUserContext>
      ) => ServerAdapter<TServerContext, YogaServer<TServerContext, TUserContext>>;

        function getSSEProcessor

        getSSEProcessor: () => ResultProcessor;

          function processRegularResult

          processRegularResult: (
          executionResult: ResultProcessorInput,
          fetchAPI: FetchAPI,
          acceptedHeader: string
          ) => Response;

            function renderGraphiQL

            renderGraphiQL: (opts: GraphiQLOptions) => string;

              function shouldRenderGraphiQL

              shouldRenderGraphiQL: ({ headers, method }: Request) => boolean;

                function useErrorCoordinate

                useErrorCoordinate: () => Plugin;

                  function useExecutionCancellation

                  useExecutionCancellation: () => Plugin;
                  • Enables experimental support for request cancelation.

                  function useReadinessCheck

                  useReadinessCheck: ({ endpoint, check }: ReadinessCheckPluginOptions) => Plugin;
                  • Adds a readiness check for Yoga by simply implementing the check option.

                  function useSchema

                  useSchema: <TServerContext = {}, TUserContext = {}>(schemaDef?: any) => any;

                    Interfaces

                    interface FetchEvent

                    interface FetchEvent extends Event {}

                      property request

                      request: Request;

                        method respondWith

                        respondWith: (response: PromiseOrValue<Response>) => void;

                          interface GraphiQLPluginConfig

                          interface GraphiQLPluginConfig<TServerContext> {}

                            property graphqlEndpoint

                            graphqlEndpoint: string;

                              property logger

                              logger?: YogaLogger;

                                property options

                                options?: GraphiQLOptionsOrFactory<TServerContext>;

                                  property render

                                  render?: GraphiQLRenderer;

                                    interface GraphQLHTTPExtensions

                                    interface GraphQLHTTPExtensions {}

                                      property headers

                                      headers?: Record<string, string>;

                                        property spec

                                        spec?: boolean;

                                          property status

                                          status?: number;

                                            interface GraphQLParams

                                            interface GraphQLParams<
                                            TVariables = Record<string, any>,
                                            TExtensions = Record<string, any>
                                            > {}

                                              property extensions

                                              extensions?: TExtensions;

                                                property operationName

                                                operationName?: string;

                                                  property query

                                                  query?: string;

                                                    property variables

                                                    variables?: TVariables;

                                                      interface LandingPageRendererOpts

                                                      interface LandingPageRendererOpts {}

                                                        property fetchAPI

                                                        fetchAPI: FetchAPI;

                                                          property graphqlEndpoint

                                                          graphqlEndpoint: string;

                                                            property request

                                                            request: Request;

                                                              property url

                                                              url: URL;

                                                                property urlPattern

                                                                urlPattern: InstanceType<FetchAPI['URLPattern']>;

                                                                  interface OnParamsEventPayload

                                                                  interface OnParamsEventPayload<TServerContext = Record<string, unknown>> {}

                                                                    property context

                                                                    context: TServerContext;

                                                                      property fetchAPI

                                                                      fetchAPI: FetchAPI;

                                                                        property params

                                                                        params: GraphQLParams;

                                                                          property paramsHandler

                                                                          paramsHandler: ParamsHandler<TServerContext>;

                                                                            property request

                                                                            request: Request;

                                                                              property setParams

                                                                              setParams: (params: GraphQLParams) => void;

                                                                                property setParamsHandler

                                                                                setParamsHandler: (handler: ParamsHandler<TServerContext>) => void;

                                                                                  property setResult

                                                                                  setResult: (result: ExecutionResult | AsyncIterable<ExecutionResult>) => void;

                                                                                    interface YogaInitialContext

                                                                                    interface YogaInitialContext extends ServerAdapterInitialContext {}

                                                                                      property params

                                                                                      params: GraphQLParams;
                                                                                      • GraphQL Parameters

                                                                                      property request

                                                                                      request: Request;
                                                                                      • An object describing the HTTP request.

                                                                                      Type Aliases

                                                                                      type BatchingOptions

                                                                                      type BatchingOptions =
                                                                                      | boolean
                                                                                      | {
                                                                                      /**
                                                                                      * You can limit the number of batched operations per request.
                                                                                      *
                                                                                      * @default 10
                                                                                      */
                                                                                      limit?: number;
                                                                                      };

                                                                                        type CORSOptions

                                                                                        type CORSOptions =
                                                                                        | {
                                                                                        origin?: string[] | string;
                                                                                        methods?: string[];
                                                                                        allowedHeaders?: string[];
                                                                                        exposedHeaders?: string[];
                                                                                        credentials?: boolean;
                                                                                        maxAge?: number;
                                                                                        }
                                                                                        | false;

                                                                                          type FetchAPI

                                                                                          type FetchAPI = ReturnType<typeof createFetch>;

                                                                                            type GraphiQLOptions

                                                                                            type GraphiQLOptions = {
                                                                                            /**
                                                                                            * Headers to be set when opening a new tab
                                                                                            */
                                                                                            defaultHeaders?: string;
                                                                                            /**
                                                                                            * An optional GraphQL string to use when no query is provided and no stored
                                                                                            * query exists from a previous session. If undefined is provided, GraphiQL
                                                                                            * will use its own default query.
                                                                                            */
                                                                                            defaultQuery?: string;
                                                                                            /**
                                                                                            * This prop can be used to define the default set of tabs, with their
                                                                                            * queries, variables, and headers. It will be used as default only if there
                                                                                            * is no tab state persisted in storage.
                                                                                            */
                                                                                            defaultTabs?: TabDefinition[];
                                                                                            /**
                                                                                            * The initial headers to render inside the header editor. Defaults to `"{}"`.
                                                                                            * The value should be a JSON encoded string, for example:
                                                                                            * `headers: JSON.stringify({Authorization: "Bearer your-auth-key"})`
                                                                                            */
                                                                                            headers?: string;
                                                                                            /**
                                                                                            * This prop toggles if the contents of the headers editor are persisted in
                                                                                            * storage.
                                                                                            */
                                                                                            shouldPersistHeaders?: boolean | undefined;
                                                                                            /**
                                                                                            * More info there: https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials
                                                                                            */
                                                                                            credentials?: RequestCredentials;
                                                                                            /**
                                                                                            * The favicon URL to display for the page. Defaults to Yoga logo.
                                                                                            */
                                                                                            favicon?: string;
                                                                                            /**
                                                                                            * The title to display at the top of the page. Defaults to `"Yoga GraphiQL"`.
                                                                                            */
                                                                                            title?: string;
                                                                                            /**
                                                                                            * Logo to be displayed in the top right corner of GraphiQL.
                                                                                            */
                                                                                            logo?: string;
                                                                                            /**
                                                                                            * Protocol for subscriptions
                                                                                            */
                                                                                            subscriptionsProtocol?: 'SSE' | 'GRAPHQL_SSE' | 'WS' | 'LEGACY_WS';
                                                                                            /**
                                                                                            * Extra headers you always want to pass with users' headers input
                                                                                            */
                                                                                            additionalHeaders?: Record<string, string>;
                                                                                            /**
                                                                                            * HTTP method to use when querying the original schema.
                                                                                            */
                                                                                            method?: 'GET' | 'POST';
                                                                                            /**
                                                                                            * Whether to use the GET HTTP method for queries when querying the original schema
                                                                                            */
                                                                                            useGETForQueries?: boolean;
                                                                                            /**
                                                                                            * "external" fragments that will be included in the query document (depending on usage)
                                                                                            */
                                                                                            externalFragments?: string;
                                                                                            /**
                                                                                            * The maximum number of executed operations to store.
                                                                                            * @default 20
                                                                                            */
                                                                                            maxHistoryLength?: number;
                                                                                            /**
                                                                                            * Whether target GraphQL server support deprecation of input values.
                                                                                            * @default false
                                                                                            */
                                                                                            inputValueDeprecation?: boolean;
                                                                                            /**
                                                                                            * Custom operation name for the introspection query.
                                                                                            */
                                                                                            introspectionQueryName?: string;
                                                                                            /**
                                                                                            * Whether to include schema description in introspection query.
                                                                                            * @default false
                                                                                            */
                                                                                            schemaDescription?: boolean;
                                                                                            /**
                                                                                            * Editor theme
                                                                                            * @default "graphiql"
                                                                                            */
                                                                                            editorTheme?: string;
                                                                                            /**
                                                                                            * Sets the key map to use when using the editor.
                                                                                            * @default 'sublime'
                                                                                            */
                                                                                            keyMap?: 'sublime' | 'emacs' | 'vim';
                                                                                            defaultEditorToolsVisibility?: boolean | 'variables' | 'headers';
                                                                                            isHeadersEditorEnabled?: boolean;
                                                                                            disableTabs?: boolean;
                                                                                            /**
                                                                                            * Whether to include `isRepeatable` flag on directives.
                                                                                            * @default false
                                                                                            */
                                                                                            directiveIsRepeatable?: boolean;
                                                                                            experimentalFragmentVariables?: boolean;
                                                                                            /**
                                                                                            * Set to `true` in order to convert all GraphQL comments (marked with # sign) to descriptions (""")
                                                                                            * GraphQL has built-in support for transforming descriptions to comments (with `print`), but not while
                                                                                            * parsing. Turning the flag on will support the other way as well (`parse`)
                                                                                            */
                                                                                            commentDescriptions?: boolean;
                                                                                            /**
                                                                                            * Timeout in milliseconds
                                                                                            */
                                                                                            timeout?: number;
                                                                                            /**
                                                                                            * Retry attempts
                                                                                            */
                                                                                            retry?: number;
                                                                                            /**
                                                                                            * The endpoint requests should be sent.
                                                                                            * Defaults to the graphql endpoint ("/graphql" by default).
                                                                                            */
                                                                                            endpoint?: string;
                                                                                            };

                                                                                              type GraphiQLOptionsOrFactory

                                                                                              type GraphiQLOptionsOrFactory<TServerContext> =
                                                                                              | GraphiQLOptions
                                                                                              | GraphiQLOptionsFactory<TServerContext>
                                                                                              | boolean;

                                                                                                type GraphiQLRenderer

                                                                                                type GraphiQLRenderer = (options: GraphiQLOptions) => PromiseOrValue<BodyInit>;

                                                                                                  type GraphQLSchemaWithContext

                                                                                                  type GraphQLSchemaWithContext<TContext> = GraphQLSchema & {
                                                                                                  _context?: TContext;
                                                                                                  };

                                                                                                    type Instrumentation

                                                                                                    type Instrumentation<TContext extends Record<string, any>> =
                                                                                                    EnvelopInstrumentation<TContext> &
                                                                                                    ServerAdapterInstrumentation & {
                                                                                                    operation?: (
                                                                                                    payload: {
                                                                                                    context: TContext;
                                                                                                    request: Request;
                                                                                                    },
                                                                                                    wrapped: () => PromiseOrValue<void>
                                                                                                    ) => PromiseOrValue<void>;
                                                                                                    requestParse?: (
                                                                                                    payload: {
                                                                                                    request: Request;
                                                                                                    },
                                                                                                    wrapped: () => MaybePromise<void>
                                                                                                    ) => MaybePromise<void>;
                                                                                                    resultProcess?: (
                                                                                                    payload: {
                                                                                                    request: Request;
                                                                                                    },
                                                                                                    wrapped: () => MaybePromise<void>
                                                                                                    ) => MaybePromise<void>;
                                                                                                    };

                                                                                                      type LandingPageRenderer

                                                                                                      type LandingPageRenderer = (
                                                                                                      opts: LandingPageRendererOpts
                                                                                                      ) => PromiseOrValue<Response>;

                                                                                                        type MaskError

                                                                                                        type MaskError = (error: unknown, message: string, isDev?: boolean) => Error;

                                                                                                          type MaybeArray

                                                                                                          type MaybeArray<T> = T | T[];

                                                                                                            type Plugin

                                                                                                            type Plugin<
                                                                                                            PluginContext extends Record<string, any> = {},
                                                                                                            TServerContext extends Record<string, any> = {},
                                                                                                            TUserContext = {}
                                                                                                            > = EnvelopPlugin<YogaInitialContext & PluginContext> &
                                                                                                            ServerAdapterPlugin<TServerContext> & {
                                                                                                            /**
                                                                                                            * onExecute hook that is invoked before the execute function is invoked.
                                                                                                            */
                                                                                                            onExecute?: OnExecuteHook<YogaInitialContext & PluginContext & TUserContext>;
                                                                                                            /**
                                                                                                            * onSubscribe hook that is invoked before the subscribe function is called.
                                                                                                            * Return a OnSubscribeHookResult for hooking into phase after the subscribe function has been called.
                                                                                                            */
                                                                                                            onSubscribe?: OnSubscribeHook<
                                                                                                            YogaInitialContext & PluginContext & TUserContext
                                                                                                            >;
                                                                                                            /**
                                                                                                            * Invoked when a plugin is initialized. You can use this hook to add other plugin you may depend on.
                                                                                                            */
                                                                                                            onPluginInit?: OnPluginInitHook<
                                                                                                            YogaInitialContext & PluginContext & TUserContext
                                                                                                            >;
                                                                                                            } & {
                                                                                                            /**
                                                                                                            * A Tracer instance that will wrap each phases of the request pipeline.
                                                                                                            * This should be used primarly as an observability tool (for monitoring, tracing, etc...).
                                                                                                            */
                                                                                                            instrumentation?: Instrumentation<
                                                                                                            YogaInitialContext & PluginContext & TUserContext
                                                                                                            >;
                                                                                                            /**
                                                                                                            * This hook is invoked at Yoga Server initialization, before it starts.
                                                                                                            * Here you can setup long running resources (like monitoring or caching clients)
                                                                                                            * or customize the Yoga instance.
                                                                                                            */
                                                                                                            onYogaInit?: OnYogaInitHook<TServerContext>;
                                                                                                            /**
                                                                                                            * This hook is invoked for any incoming GraphQL HTTP request and is invoked before attempting
                                                                                                            * to parse the GraphQL parameters. Here you can manipulate the request, set a custom request
                                                                                                            * parser or apply security measures such as checking for access tokens etc.
                                                                                                            */
                                                                                                            onRequestParse?: OnRequestParseHook<TServerContext>;
                                                                                                            /**
                                                                                                            * This hook is invoked for an incoming GraphQL request after the GraphQL parameters
                                                                                                            * (query, variables, extensions and operationName) have been ATTEMPTED to be parsed.
                                                                                                            *
                                                                                                            * Within this hook you can manipulate and customize the parameters or even implement a whole
                                                                                                            * new way of parsing the parameters.
                                                                                                            *
                                                                                                            * In addition to that you could also short-circuit and skip the GraphQL execution.
                                                                                                            */
                                                                                                            onParams?: OnParamsHook<TServerContext>;
                                                                                                            /**
                                                                                                            * This hook is invoked for each result produced for GraphQL operation, before it is processed
                                                                                                            * to be sent to client.
                                                                                                            *
                                                                                                            * In particular, if a request contains batched operations, this hook is called once of each
                                                                                                            * operation.
                                                                                                            *
                                                                                                            * Here, you can modify the result, to add monitoring or instrumentation extensions for example.
                                                                                                            */
                                                                                                            onExecutionResult?: OnExecutionResultHook<TServerContext>;
                                                                                                            /**
                                                                                                            * This hook is invoked after a GraphQL request has been processed and before the response is
                                                                                                            * forwarded to the client. Here you can customize what transport/response processor format
                                                                                                            * should be used for sending the result over the wire.
                                                                                                            */
                                                                                                            onResultProcess?: OnResultProcess<TServerContext>;
                                                                                                            };

                                                                                                              type YogaMaskedErrorOpts

                                                                                                              type YogaMaskedErrorOpts = {
                                                                                                              maskError: MaskError;
                                                                                                              errorMessage: string;
                                                                                                              isDev?: boolean;
                                                                                                              };

                                                                                                                type YogaSchemaDefinition

                                                                                                                type YogaSchemaDefinition<TServerContext, TUserContext> =
                                                                                                                | PromiseOrValue<
                                                                                                                GraphQLSchemaWithContext<
                                                                                                                TServerContext & YogaInitialContext & TUserContext
                                                                                                                >
                                                                                                                >
                                                                                                                | ((
                                                                                                                context: TServerContext & {
                                                                                                                request: YogaInitialContext['request'];
                                                                                                                }
                                                                                                                ) => PromiseOrValue<
                                                                                                                GraphQLSchemaWithContext<
                                                                                                                TServerContext & YogaInitialContext & TUserContext
                                                                                                                >
                                                                                                                >);

                                                                                                                  type YogaServerInstance

                                                                                                                  type YogaServerInstance<
                                                                                                                  TServerContext extends Record<string, any>,
                                                                                                                  TUserContext extends Record<string, any>
                                                                                                                  > = ServerAdapter<TServerContext, YogaServer<TServerContext, TUserContext>>;

                                                                                                                    type YogaServerOptions

                                                                                                                    type YogaServerOptions<TServerContext, TUserContext> = Omit<
                                                                                                                    ServerAdapterOptions<TServerContext>,
                                                                                                                    'plugins'
                                                                                                                    > & {
                                                                                                                    /**
                                                                                                                    * Enable/disable logging or provide a custom logger.
                                                                                                                    * @default true
                                                                                                                    */
                                                                                                                    logging?: boolean | YogaLogger | LogLevel | undefined;
                                                                                                                    /**
                                                                                                                    * Prevent leaking unexpected errors to the client. We highly recommend enabling this in production.
                                                                                                                    * If you throw `EnvelopError`/`GraphQLError` within your GraphQL resolvers then that error will be sent back to the client.
                                                                                                                    *
                                                                                                                    * You can lean more about this here:
                                                                                                                    * @see https://the-guild.dev/graphql/yoga-server/docs/features/error-masking
                                                                                                                    *
                                                                                                                    * @default true
                                                                                                                    */
                                                                                                                    maskedErrors?: boolean | Partial<YogaMaskedErrorOpts> | undefined;
                                                                                                                    /**
                                                                                                                    * Context
                                                                                                                    */
                                                                                                                    context?:
                                                                                                                    | ((
                                                                                                                    initialContext: YogaInitialContext & TServerContext
                                                                                                                    ) => Promise<TUserContext> | TUserContext)
                                                                                                                    | Promise<TUserContext>
                                                                                                                    | TUserContext
                                                                                                                    | undefined;
                                                                                                                    cors?: Parameters<typeof useCORS>[0] | undefined;
                                                                                                                    /**
                                                                                                                    * GraphQL endpoint
                                                                                                                    * So you need to define it explicitly if GraphQL API lives in a different path other than `/graphql`
                                                                                                                    *
                                                                                                                    * @default "/graphql"
                                                                                                                    */
                                                                                                                    graphqlEndpoint?: string | undefined;
                                                                                                                    /**
                                                                                                                    * Readiness check endpoint
                                                                                                                    *
                                                                                                                    * @default "/health"
                                                                                                                    */
                                                                                                                    healthCheckEndpoint?: string | undefined;
                                                                                                                    /**
                                                                                                                    * Whether the landing page should be shown.
                                                                                                                    */
                                                                                                                    landingPage?: boolean | LandingPageRenderer | undefined;
                                                                                                                    /**
                                                                                                                    * GraphiQL options
                                                                                                                    *
                                                                                                                    * @default true
                                                                                                                    */
                                                                                                                    graphiql?: GraphiQLOptionsOrFactory<TServerContext> | undefined;
                                                                                                                    renderGraphiQL?:
                                                                                                                    | ((options: GraphiQLOptions) => PromiseOrValue<BodyInit>)
                                                                                                                    | undefined;
                                                                                                                    schema?: YogaSchemaDefinition<TServerContext, TUserContext> | undefined;
                                                                                                                    /**
                                                                                                                    * Envelop Plugins
                                                                                                                    * @see https://envelop.dev/plugins
                                                                                                                    */
                                                                                                                    plugins?:
                                                                                                                    | Array<
                                                                                                                    | Plugin<TUserContext & TServerContext & YogaInitialContext>
                                                                                                                    | Plugin
                                                                                                                    | {}
                                                                                                                    >
                                                                                                                    | undefined;
                                                                                                                    parserAndValidationCache?: boolean | ParserAndValidationCacheOptions | undefined;
                                                                                                                    fetchAPI?: Partial<Record<keyof FetchAPI, any>> | undefined;
                                                                                                                    /**
                                                                                                                    * GraphQL Multipart Request spec support
                                                                                                                    *
                                                                                                                    * @see https://github.com/jaydenseric/graphql-multipart-request-spec
                                                                                                                    *
                                                                                                                    * @default true
                                                                                                                    */
                                                                                                                    multipart?: boolean | undefined;
                                                                                                                    id?: string | undefined;
                                                                                                                    /**
                                                                                                                    * Batching RFC Support configuration
                                                                                                                    *
                                                                                                                    * @see https://github.com/graphql/graphql-over-http/blob/main/rfcs/Batching.md
                                                                                                                    *
                                                                                                                    * @default false
                                                                                                                    */
                                                                                                                    batching?: BatchingOptions | undefined;
                                                                                                                    /**
                                                                                                                    * By default, GraphQL Yoga does not allow parameters in the request body except `query`, `variables`, `extensions`, and `operationName`.
                                                                                                                    *
                                                                                                                    * This option allows you to specify additional parameters that are allowed in the request body.
                                                                                                                    *
                                                                                                                    * @default []
                                                                                                                    *
                                                                                                                    * @example ['doc_id', 'id']
                                                                                                                    */
                                                                                                                    extraParamNames?: string[] | undefined;
                                                                                                                    /**
                                                                                                                    * Allowed headers. Headers not part of this list will be striped out.
                                                                                                                    */
                                                                                                                    allowedHeaders?: {
                                                                                                                    /** Allowed headers for outgoing responses */
                                                                                                                    response?: string[] | undefined;
                                                                                                                    /** Allowed headers for ingoing requests */
                                                                                                                    request?: string[] | undefined;
                                                                                                                    };
                                                                                                                    };
                                                                                                                    • Configuration options for the server

                                                                                                                    Package Files (15)

                                                                                                                    Dependencies (12)

                                                                                                                    Dev Dependencies (0)

                                                                                                                    No dev dependencies.

                                                                                                                    Peer Dependencies (1)

                                                                                                                    Badge

                                                                                                                    To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                                                                                                                    You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/graphql-yoga.

                                                                                                                    • Markdown
                                                                                                                      [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/graphql-yoga)
                                                                                                                    • HTML
                                                                                                                      <a href="https://www.jsdocs.io/package/graphql-yoga"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>