APIスライス:コード分割と生成
各APIスライスでは、初期のAPIスライスが定義された後に、実行時に追加のエンドポイント定義を挿入できます。これは、非常に多くのエンドポイントを持つアプリにとって有益です。
個々のAPIスライスエンドポイント定義は、複数のファイルに分割することもできます。これは主に、APIスキーマファイルからコード生成されたAPIスライスを扱う際に役立ち、自動生成されたエンドポイント定義に、追加のカスタム動作と設定を追加できます。
各APIスライスオブジェクトには、これらのユースケースをサポートする`injectEndpoints`関数と`enhanceEndpoints`関数があります。
injectEndpoints
シグネチャ
const injectEndpoints = (endpointOptions: InjectedEndpointOptions) =>
EnhancedApiSlice
interface InjectedEndpointOptions {
endpoints: (build: EndpointBuilder) => NewEndpointDefinitions
/**
* Optionally allows endpoints to be overridden if defined by multiple `injectEndpoints` calls.
*
* If set to `true`, will override existing endpoints with the new definition.
* If set to `'throw'`, will throw an error if an endpoint is redefined with a different definition.
* If set to `false` (or unset), will not override existing endpoints with the new definition, and log a warning in development.
*/
overrideExisting?: boolean | 'throw'
}
説明
createApi.endpoints
に渡すのと同じendpoints
ビルダーコールバックを含むオプションオブジェクトを受け取ります。そのビルダーを使用して定義されたエンドポイント定義は、浅いマージを使用してこのAPIスライスの既存のエンドポイント定義にマージされるため、新しいエンドポイント定義は、同じ名前の既存のエンドポイントを上書きします。
結合されたエンドポイント定義を含む、更新され拡張されたバージョンのAPIスライスオブジェクトを返します。
overrideExisting
がtrue
に設定されていない限り、エンドポイントは上書きされません。そうでない場合、エンドポイント定義に名前の衝突がある場合に通知する開発モードの警告が表示されます。
このメソッドは、主にコード分割とホットリロードに役立ちます。
enhanceEndpoints
シグネチャ
const enhanceEndpoints = (endpointOptions: EnhanceEndpointsOptions) =>
EnhancedApiSlice
interface EnhanceEndpointsOptions {
addTagTypes?: readonly string[]
endpoints?: Record<string, Partial<EndpointDefinition>>
}
説明
提供されたタグタイプまたはエンドポイント定義は、このAPIスライスの既存のエンドポイント定義にマージされます。`injectEndpoints`とは異なり、部分的なエンドポイント定義は既存の定義を置き換えませんが、定義ごとにマージされます(つまり、`Object.assign(existingEndpoint, newPartialEndpoint)`)。
結合されたエンドポイント定義を含む、更新され拡張されたバージョンのAPIスライスオブジェクトを返します。
これは主に、OpenAPIなどのAPIスキーマファイルからコード生成されたAPIスライスオブジェクトを取得し、生成されたエンドポイント定義の上に、キャッシュ無効化管理に関する追加の特定の手書きの設定を追加するのに役立ちます。
たとえば、`enhanceEndpoints`を使用して、`providesTags`、`invalidatesTags`、`keepUnusedDataFor`の値を変更することにより、キャッシング動作を変更できます。
- TypeScript
- JavaScript
import { api } from './api'
const enhancedApi = api.enhanceEndpoints({
addTagTypes: ['User'],
endpoints: {
getUserByUserId: {
providesTags: ['User'],
},
patchUserByUserId: {
invalidatesTags: ['User'],
},
// alternatively, define a function which is called with the endpoint definition as an argument
getUsers(endpoint) {
endpoint.providesTags = ['User']
endpoint.keepUnusedDataFor = 120
},
},
})
import { api } from './api'
const enhancedApi = api.enhanceEndpoints({
addTagTypes: ['User'],
endpoints: {
getUserByUserId: {
providesTags: ['User'],
},
patchUserByUserId: {
invalidatesTags: ['User'],
},
// alternatively, define a function which is called with the endpoint definition as an argument
getUsers(endpoint) {
endpoint.providesTags = ['User']
endpoint.keepUnusedDataFor = 120
},
},
})