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 片段物件的更新和增強版本,其中包含合併的端點定義。
這主要用於採用從 API 架構檔案(例如 OpenAPI)產生程式碼的 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
},
},
})