new·Earn with mozg — 20% of every monthSend somebody here and take a fifth of every plan payment they make, for as long as they keep paying — not a bounty on the first invoice. Your handle is the link, the window is thirty days, and the commission lands on your balance the second they pay. Free to join: if you have signed in, you already have the link. mozg.sh/earnall news →
mozg.beta
Sign in

Redux Toolkit · RTK Query · all subjects

openapi code generation

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

Run OpenAPI code generation from CLI

Execute code generation with: npx @rtk-query/codegen-openapi openapi-config.ts, where openapi-config.ts is the path to your configuration file.

RTK Query code generation overview

RTK Query's API and architecture is oriented around declaring API endpoints up front, which lends itself well to automatically generating API slice definitions from external API schema definitions such as OpenAPI and GraphQL.

GraphQL code generation plugin

Redux Toolkit provides a Plugin for GraphQL Codegen at https://www.graphql-code-generator.com/docs/plugins/typescript-rtk-query. An example project demonstrating its usage is available at https://github.com/reduxjs/redux-toolkit/tree/master/examples/query/react/graphql-codegen.

OpenAPI code generation package

RTK Query provides the @rtk-query/codegen-openapi package for code generation from OpenAPI schemas. The source code is located at https://github.com/reduxjs/redux-toolkit/tree/master/packages/rtk-query-codegen-openapi.

Create empty API for code generation

To prepare for OpenAPI code generation, create an empty API slice using createApi with fetchBaseQuery and an empty endpoints object. This empty API will have generated endpoints injected into it later. Example: createApi({ baseQuery: fetchBaseQuery({ baseUrl: '/' }), endpoints: () => ({}) }).

OpenAPI code generation config file structure

An OpenAPI codegen config file contains: schemaFile (URL to OpenAPI spec), apiFile (path to empty API file), apiImport (name of API export to use), outputFile (where to write generated code), exportName (name for generated API export), and hooks (boolean or object to generate hooks).

Generating tags from OpenAPI tags field

If your OpenAPI specification uses tags, you can specify the tag option in codegen config to result in all generated endpoints having providesTags/invalidatesTags declarations for the tags of their respective operation definition. This generates only string tags with no IDs, which may lead to unnecessary invalidation and requests.

Tag generation alternatives

When OpenAPI tag generation leads to too much invalidation, use either: (1) endpointOverrides to customize tags for specific endpoints during code generation, or (2) enhanceEndpoints after generation to manually add more specific providesTags/invalidatesTags with IDs.

Programmatic OpenAPI code generation usage

Use generateEndpoints function programmatically: await generateEndpoints({ apiFile: './fixtures/emptyApi.ts', schemaFile: resolve(__dirname, 'fixtures/petstore.json'), filterEndpoints: ['getPetById', 'addPet'], hooks: true }).

OpenAPI codegen config options - SimpleUsage interface

SimpleUsage interface properties: apiFile (string, required), schemaFile (string, required), apiImport (string, optional), exportName (string, optional), argSuffix (string, optional), operationNameSuffix (string, optional), operationIdTransformer ('camelCase' | 'none' | function, optional), responseSuffix (string, optional), hooks (boolean or object with queries/lazyQueries/mutations booleans, optional), tag (boolean, optional), outputFile (string, required), filterEndpoints (string | RegExp | EndpointMatcherFunction | array, optional), endpointOverrides (EndpointOverrides[], optional), flattenArg (boolean, optional), useEnumType (boolean, optional), enumStyle ('union' | 'enum' | 'as-const', optional), outputRegexConstants (boolean, optional), httpResolverOptions (SwaggerParser.HTTPResolverOptions, optional).

FilterEndpoints option behavior

The filterEndpoints config option filters generated endpoints. Endpoints are transformed to camelCase by default (e.g., login_user becomes loginUser). filterEndpoints is checked against the transformed endpoint name after applying operationIdTransformer. Can be a string, RegExp, EndpointMatcherFunction, or array of these types.

OperationIdTransformer default behavior

By default, each operation's operationId is converted to camelCase using lodash camelCase. This means consecutive uppercase letters are lowercased — for example, fetchMyJWTPlease becomes fetchMyJwtPlease.

OperationIdTransformer options

Three operationIdTransformer options: (1) 'camelCase' (default) - applies lodash camelCase matching prior behavior, (2) 'none' - uses raw operationId verbatim preserving casing, (3) custom function - applies custom transformation for full control.

OperationIdTransformer 'none' mode requirement

When operationIdTransformer is 'none' or a custom function, every operation in the schema must have an operationId. The codegen will throw an error if any operation is missing one.

FilterEndpoints with operationIdTransformer

When using filterEndpoints together with operationIdTransformer, the filter is matched against the transformed name, not the raw operationId.

Endpoint type override

If an endpoint is generated as a mutation instead of a query or vice versa, override it using endpointOverrides with pattern and type properties. Example: { pattern: 'loginUser', type: 'mutation' }.

Parameter filtering in endpoint overrides

Filter parameters included in an endpoint using endpointOverrides with parameterFilter property (path parameters cannot be filtered). ParameterFilter can be a RegExp or ParameterMatcherFunction. Example: { pattern: 'loginUser', parameterFilter: /^x-/ } includes only parameters beginning with 'x-'.

Override tags in code generation

Override providesTags and invalidatesTags for any endpoint using endpointOverrides with pattern, providesTags, and/or invalidatesTags properties. Tag overrides take precedence over auto-generated tags from the OpenAPI tags field. Use empty array to explicitly remove tags. Both providesTags and invalidatesTags can be set on any endpoint type.

Tag override behaviors and use cases

Tag overrides are useful when: OpenAPI tags don't match your caching strategy, you need more specific cache invalidation than default tag generation provides, a mutation should provide tags (e.g., login returning user data), or a query should invalidate tags (e.g., polling triggering cache updates).

Tag overrides with tag: false

When using tag overrides with tag: false, the overridden tags will be emitted in the generated code but won't be automatically added to addTagTypes. You may need to manually add your custom tags to the base API's tagTypes array.

Generating hooks from OpenAPI codegen

Setting hooks: true generates useQuery and useMutation hook exports. For useLazyQuery hooks or more granular control, pass an object: { queries: boolean; lazyQueries: boolean; mutations: boolean }.

Enum generation styles

Three enumStyle options for OpenAPI enum definitions: (1) 'union' (default) - union of string literals like type Status = 'available' | 'pending', (2) 'enum' - TypeScript enum, (3) 'as-const' - const object with companion type for runtime values like an enum while remaining tree-shakeable and compatible with isolatedModules.

useEnumType option deprecation

useEnumType: true is equivalent to enumStyle: 'enum'. If both options are specified, enumStyle takes precedence.

Generate regex constants from OpenAPI pattern keyword

Set outputRegexConstants: true to export regex patterns from OpenAPI schema pattern keyword as JavaScript regex constants. Only string-type properties with non-empty pattern values generate constants. The constant name follows format {typeName}{propertyName}Pattern in camelCase.

Regex constants generation example

For OpenAPI schema properties with patterns like email with pattern '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$' and phone with pattern '^\+?[1-9]\d{1,14}$', the codegen generates: export const userEmailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/ and export const userPhonePattern = /^\+?[1-9]\d{1,14}$/.

Multiple output files in OpenAPI codegen

Configure multiple output files with outputFiles object mapping file paths to config objects with filterEndpoints option. Example: { './src/store/user.ts': { filterEndpoints: [/user/i] }, './src/store/order.ts': { filterEndpoints: [/order/i] } }.

Custom HTTP resolver options for OpenAPI fetch

Use httpResolverOptions to customize the HTTP request issued to fetch your OpenAPI schema. This object is passed directly to the SwaggerParser instance. Can pass custom headers or set custom request timeout. Example: { timeout: 30_000, headers: { Accept: 'application/json', Authorization: 'Basic...' } }.

Export additional schemas from OpenAPI codegen

By default, only schemas referenced in endpoint definitions are exported. Set exportAllSchemas: true to export all available schemas whether they're referenced in endpoint definitions or not. Useful for extra models defined but not directly used in endpoints.

Give your agent this brain