コード生成
RTK QueryのAPIとアーキテクチャは、APIエンドポイントを事前に宣言することを中心に構成されています。これにより、OpenAPIやGraphQLなどの外部APIスキーマ定義からAPIスライス定義を自動生成することが容易になります。
コード生成機能の早期プレビュー版が、別のツールとして利用可能です。
GraphQL
GraphQL Codegenのプラグインを提供しています。そのドキュメントは、graphql-codegenのホームページで確認できます。
その使い方に関する完全な例は、このサンプルプロジェクトで確認できます。
OpenAPI
OpenAPIスキーマからのRTK Queryコード生成のためのパッケージを提供しています。これは@rtk-query/codegen-openapi
として公開されており、ソースコードはpackages/rtk-query-codegen-openapi
にあります。
使い方
次のようにcreateApi
を使って空のAPIを作成します。
// Or from '@reduxjs/toolkit/query' if not using the auto-generated hooks
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
// initialize an empty api service that we'll inject endpoints into later as needed
export const emptySplitApi = createApi({
baseQuery: fetchBaseQuery({ baseUrl: '/' }),
endpoints: () => ({}),
})
次のような内容の構成ファイル(json、js、またはts)を生成します。
import type { ConfigFile } from '@rtk-query/codegen-openapi'
const config: ConfigFile = {
schemaFile: 'https://petstore3.swagger.io/api/v3/openapi.json',
apiFile: './src/store/emptyApi.ts',
apiImport: 'emptySplitApi',
outputFile: './src/store/petApi.ts',
exportName: 'petApi',
hooks: true,
}
export default config
その後、コードジェネレータを呼び出します。
npx @rtk-query/codegen-openapi openapi-config.ts
タグの生成
OpenAPI仕様でタグを使用している場合、コード生成時にtag
オプションを指定できます。
これにより、生成されたすべてのエンドポイントに、それぞれの操作定義のtags
に対してprovidesTags
/ invalidatesTags
の宣言が追加されます。
これはIDのない文字列タグのみを生成するため、ミューテーション時に過剰な無効化が発生し、不必要なリクエストが行われる可能性があります。
その場合でも、生成されたAPIの上でenhanceEndpoints
を使用し、providesTags
/ invalidatesTags
を手動で宣言して、タグを手動で指定することをお勧めします。
プログラムによる使用
import { generateEndpoints } from '@rtk-query/codegen-openapi'
const api = await generateEndpoints({
apiFile: './fixtures/emptyApi.ts',
schemaFile: resolve(__dirname, 'fixtures/petstore.json'),
filterEndpoints: ['getPetById', 'addPet'],
hooks: true,
})
構成ファイルのオプション
簡単な使い方
interface SimpleUsage {
apiFile: string
schemaFile: string
apiImport?: string
exportName?: string
argSuffix?: string
responseSuffix?: string
hooks?:
| boolean
| { queries: boolean; lazyQueries: boolean; mutations: boolean }
tag?: boolean
outputFile: string
filterEndpoints?:
| string
| RegExp
| EndpointMatcherFunction
| Array<string | RegExp | EndpointMatcherFunction>
endpointOverrides?: EndpointOverrides[]
flattenArg?: boolean
}
export type EndpointMatcherFunction = (
operationName: string,
operationDefinition: OperationDefinition,
) => boolean
エンドポイントのフィルタリング
いくつかのエンドポイントのみを含めたい場合は、filterEndpoints
構成オプションを使用してエンドポイントをフィルタリングできます。
const filteredConfig: ConfigFile = {
// ...
// should only have endpoints loginUser, placeOrder, getOrderById, deleteOrder
filterEndpoints: ['loginUser', /Order/],
}
エンドポイントのオーバーライド
エンドポイントがクエリではなくミューテーションとして生成された場合、またはその逆の場合、それをオーバーライドできます。
const withOverride: ConfigFile = {
// ...
endpointOverrides: [
{
pattern: 'loginUser',
type: 'mutation',
},
],
}
フックの生成
hooks: true
を設定すると、useQuery
およびuseMutation
フックのエクスポートが生成されます。また、useLazyQuery
フックを生成したい場合や、より詳細な制御を行いたい場合は、{ queries: boolean; lazyQueries: boolean; mutations: boolean }
の形式のオブジェクトを渡すこともできます。
複数の出力ファイル
const config: ConfigFile = {
schemaFile: 'https://petstore3.swagger.io/api/v3/openapi.json',
apiFile: './src/store/emptyApi.ts',
outputFiles: {
'./src/store/user.ts': {
filterEndpoints: [/user/i],
},
'./src/store/order.ts': {
filterEndpoints: [/order/i],
},
'./src/store/pet.ts': {
filterEndpoints: [/pet/i],
},
},
}