new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Redux Toolkit · RTK Query · all subjects

createapi/schema

38 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Schema validation in endpoints

Endpoints can have schemas for runtime validation of query args, responses, and errors. Any Standard Schema compliant library can be used. When used with TypeScript, schemas can infer the type of values instead of requiring explicit type declaration.

Schema failure handling is fatal by default

By default, schema failures are treated as fatal, meaning that normal error handling such as tag invalidation will not be executed. To treat schema failures as non-fatal, you must provide a catchSchemaFailure function to convert the schema failure into an error shape matching the base query errors.

catchSchemaFailure example

const api = createApi({ baseQuery: fetchBaseQuery({ baseUrl: '/' }), catchSchemaFailure: (error, info) => ({ status: 'CUSTOM_ERROR', error: error.schemaName + ' failed validation', data: error, }), endpoints: (build) => ({ // ... }), })

argSchema parameter

argSchema is an optional parameter for endpoint definitions that validates the query or mutation arguments using a Standard Schema compliant library.

responseSchema parameter

responseSchema is an optional parameter for endpoint definitions that validates the final transformed response value that ends up in RTK Query's cache and hooks.

errorResponseSchema parameter

errorResponseSchema is an optional parameter that validates the transformed error shape that ends up in RTK Query's cache and hooks after transformErrorResponse.

rawErrorResponseSchema parameter

rawErrorResponseSchema is an optional parameter for query endpoints only (not applicable with queryFn) that validates the error value returned by baseQuery before transformErrorResponse runs. This is the error-side equivalent of rawResponseSchema.

metaSchema parameter

metaSchema is an optional parameter for endpoint definitions that validates the meta value using a Standard Schema compliant library.

onSchemaFailure parameter

onSchemaFailure is an optional parameter for createApi that can be set globally and overridden per-endpoint. It determines how schema validation failures are handled.

skipSchemaValidation parameter

skipSchemaValidation is an optional parameter for createApi that can be set globally and overridden per-endpoint. When true, schema validation is skipped for that endpoint.

RTK Query code generation from OpenAPI

RTK Query has an experimental code generation tool that takes an OpenAPI spec or GraphQL schema and generates a typed API client, with methods available for enhancing the generated client after generation.

Schema validation with Standard Schema

Endpoints can have schemas for runtime validation of query args, responses, and errors using any Standard Schema compliant library. When explicitly specifying type parameters for queries and mutations, schemas must match the types provided.

Implicit typing from schemas

Type parameters can be omitted from endpoints and instead inferred from schemas. The arg type is inferred from the query function signature, and result type is inferred from responseSchema (or rawResponseSchema for pre-transformation type).

Example: implicitly typed endpoints from responseSchema

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react' import * as v from 'valibot' const postSchema = v.object({ id: v.number(), name: v.string(), }) type Post = v.InferOutput<typeof postSchema> const api = createApi({ baseQuery: fetchBaseQuery({ baseUrl: '/' }), endpoints: (build) => ({ getPost: build.query({ query: ({ id }: { id: number }) => `/post/${id}`, responseSchema: postSchema, }), getTransformedPost: build.query({ query: ({ id }: { id: number }) => `/post/${id}`, rawResponseSchema: postSchema, transformResponse: (response) => ({ ...response, published_at: new Date(response.published_at), }), }), }), }) This shows inferring arg type from query signature and result type from responseSchema, with rawResponseSchema for pre-transformation validation.

Schemas must not perform type-changing transformations

Schemas should not perform any transformation that would change the type of the value. Type-changing transformations like string to Date must be done using transformResponse or transformErrorResponse (with query) or inside queryFn (with queryFn), not within the schema.

Example: correct schema usage with transformResponse

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react' import * as v from 'valibot' const postSchema = v.object({ id: v.number(), name: v.string(), published_at: v.string(), }) type RawPost = v.InferOutput<typeof postSchema> type Post = Omit<RawPost, 'published_at'> & { published_at: Date } const api = createApi({ baseQuery: fetchBaseQuery({ baseUrl: '/' }), endpoints: (build) => ({ getPost: build.query<Post, { id: number }>({ query: ({ id }) => `/post/${id}`, rawResponseSchema: postSchema, transformResponse: (response) => ({ ...response, published_at: new Date(response.published_at), }), }), }), }) This shows using rawResponseSchema to validate pre-transformation data, then performing type change in transformResponse.

RTK Query code generation from OpenAPI schemas

RTK Query provides automated code generation capabilities for creating API slice definitions from external schema definitions, including OpenAPI and GraphQL. The package @rtk-query/codegen-openapi is available for generating RTK Query code from OpenAPI schemas.

Create empty API for OpenAPI code generation

To use RTK Query OpenAPI code generation, first create an empty API using createApi with an empty endpoints object. This empty API serves as a base that will have generated endpoints injected into it. The example uses fetchBaseQuery with baseUrl '/' and can be imported from '@reduxjs/toolkit/query/react' or '@reduxjs/toolkit/query'.

OpenAPI code generation configuration file options

Configuration for @rtk-query/codegen-openapi codegen includes: schemaFile (string, required - URL or file path to OpenAPI schema), apiFile (string, required - path to empty API file), apiImport (string, optional - name of API import from apiFile), outputFile (string, required - path for generated code output), exportName (string, optional - name to export from output file), hooks (boolean or object with queries, lazyQueries, mutations properties, optional - whether to generate hooks), tag (boolean, optional - generate providesTags/invalidatesTags from OpenAPI tags), filterEndpoints (string, RegExp, function, or array - filter which endpoints to generate), endpointOverrides (array - customize generated endpoints), argSuffix (string, optional - suffix for argument types), operationNameSuffix (string, optional - suffix for operation names), operationIdTransformer ('camelCase', 'none', or function - control endpoint name generation), responseSuffix (string, optional - suffix for response types), flattenArg (boolean, optional - flatten argument structure), useEnumType (boolean, optional - generate TypeScript enums), enumStyle ('union', 'enum', or 'as-const' - control enum generation), outputRegexConstants (boolean, optional - export regex constants for pattern validation), httpResolverOptions (object, optional - SwaggerParser HTTP options), exportAllSchemas (boolean, optional - export all schemas regardless of endpoint reference).

OpenAPI codegen command line usage

After creating an empty API file and config file, run the OpenAPI code generator using: npx @rtk-query/codegen-openapi openapi-config.ts (where openapi-config.ts is the configuration file path).

Programmatic OpenAPI code generation

RTK Query OpenAPI codegen can be used programmatically by importing generateEndpoints from '@rtk-query/codegen-openapi' and calling it with options including apiFile, schemaFile, filterEndpoints array to specify which endpoints to generate, and hooks boolean.

OpenAPI codegen with Node.js child process

OpenAPI code generation can be executed via Node.js child process by resolving the CLI path from '@rtk-query/codegen-openapi/cli' and executing it with tsx, esr, or ts-node, passing the config file as an argument.

Filtering endpoints in OpenAPI code generation

The filterEndpoints configuration option filters which endpoints to generate. Endpoints are transformed to camelCase by default (e.g., login_user becomes loginUser). The filter is checked against the transformed endpoint name after applying operationIdTransformer. filterEndpoints accepts string, RegExp, EndpointMatcherFunction, or an array of these types.

operationIdTransformer default behavior and options

By default, each operation's operationId is converted to camelCase using lodash camelCase, so consecutive uppercase letters are lowercased (e.g., fetchMyJWTPlease becomes fetchMyJwtPlease). The operationIdTransformer option supports three values: 'camelCase' (default, applies lodash camelCase), 'none' (uses raw operationId verbatim preserving casing), or a custom function (operationId: string) => string for full control over transformation.

operationIdTransformer requirement for 'none' and custom functions

When operationIdTransformer is set to 'none' or a custom function, every operation in the OpenAPI schema must have an operationId defined. The codegen will throw an error if any operation is missing one. When using filterEndpoints with operationIdTransformer, the filter is matched against the transformed name, not the original operationId.

OpenAPI endpoint type override

If an endpoint is generated as a mutation instead of a query or vice versa, the endpointOverrides configuration can override this. An override object with pattern (string, RegExp, or function matching endpoint name) and type ('mutation' or 'query') will change the endpoint type for matching endpoints.

OpenAPI parameter filtering in endpoint overrides

The endpointOverrides configuration supports parameterFilter to filter parameters included for an endpoint, excluding path parameters. The parameterFilter accepts RegExp or ParameterMatcherFunction. A function receives (name: string, parameter: Parameter) and returns boolean. For example, filtering to only include parameters beginning with 'x-' or excluding header parameters.

OpenAPI tag overrides in code generation

Tag overrides in endpointOverrides configuration allow customizing providesTags and invalidatesTags for any endpoint. Overrides take precedence over auto-generated tags from the OpenAPI tags field. An empty array can be used to explicitly remove tags from an endpoint. Both providesTags and invalidatesTags can be set on any endpoint type regardless of whether the global tag option is enabled.

OpenAPI tag generation from schema tags

When the tag option is enabled in OpenAPI codegen configuration, all generated endpoints will have providesTags/invalidatesTags declarations for the tags of their respective operation definition from the OpenAPI schema. Note that this results only in string tags with no IDs, which may lead to scenarios where too much is invalidated. Use endpointOverrides to customize tags for specific endpoints, or use enhanceEndpoints after generation to manually add more specific providesTags/invalidatesTags with IDs.

Generating hooks from OpenAPI schema

Setting hooks: true in the OpenAPI codegen configuration will generate useQuery and useMutation hook exports. For more granular control, pass an object: { queries: boolean; lazyQueries: boolean; mutations: boolean } to control which hook types are generated.

Enum generation styles in OpenAPI codegen

The enumStyle option controls how OpenAPI enum definitions are generated: 'union' (default) generates a union of string literals like type Status = 'available' | 'pending', 'enum' generates a TypeScript enum like enum Status { Available = 'available' }, 'as-const' generates a const object with companion type that is tree-shakeable and compatible with isolatedModules.

Generating regex constants from OpenAPI pattern keyword

Setting outputRegexConstants: true in OpenAPI codegen configuration exports regex constants for schema properties that use the pattern keyword for regex validation. The generated constant name follows the format {typeName}{propertyName}Pattern in camelCase. Only string-type properties with non-empty pattern values generate constants, and these can be used for client-side validation.

Multiple output files in OpenAPI code generation

The outputFiles configuration option allows generating multiple output files from a single OpenAPI schema. It accepts an object mapping output file paths to filter configurations. Each filter configuration can include filterEndpoints to specify which endpoints go to each output file.

Custom HTTP resolver options for OpenAPI schema fetching

The httpResolverOptions configuration passes custom HTTP options directly to the SwaggerParser instance that fetches the OpenAPI schema. This allows customizing the HTTP request, such as setting custom headers or timeout values, for remote schema files.

exportAllSchemas configuration in OpenAPI codegen

By default, only schemas referenced in endpoint definitions are exported from OpenAPI code generation. Setting exportAllSchemas: true exports all available schemas defined in the OpenAPI specification, whether they are referenced in endpoint definitions or not. This is useful when schemas are marked as extra models but not directly used as endpoint parameters or responses.

Tag overrides with tag: false in OpenAPI codegen

When using tag overrides with tag: false, the overridden tags will be emitted in the generated code but will not be automatically added to addTagTypes. Manual addition of custom tags to the base API's tagTypes array may be necessary.

Runtime validation with Standard Schema

Endpoints can use any Standard Schema compliant library for runtime validation of query args, responses, and errors. The most common usage is responseSchema to validate the response from the server, or rawResponseSchema when using transformResponse.

Example: responseSchema and rawResponseSchema usage

Example showing getPost with responseSchema: postSchema to validate raw response, and getTransformedPost with rawResponseSchema: postSchema (validates before transform) and transformResponse callback, then responseSchema: transformedPost (validates after transform). This demonstrates schema validation before and after response transformation.

Give your agent this brain