Usage > Code Generation: automated creation of API code">Usage > Code Generation: automated creation of API code">
跳到主要內容

程式碼產生

RTK Query 的 API 和架構以預先宣告 API 端點為導向。這非常適合從外部 API 架構定義(例如 OpenAPI 和 GraphQL)自動產生 API 區段定義。

我們有早期預覽版本的程式碼產生功能,可作為獨立工具使用。

GraphQL

我們提供 GraphQL Codegen 外掛程式。您可以在 graphql-codegen 首頁上找到相關文件。

如需如何使用它的完整範例,您可以參閱 這個範例專案

OpenAPI

我們提供一個套件,用於從 OpenAPI 架構產生 RTK Query 程式碼。它以 @rtk-query/codegen-openapi 發布,你可以在 packages/rtk-query-codegen-openapi 找到原始碼。

用法

使用 createApi 建立一個空的 API,如下所示

src/store/emptyApi.ts
// 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),內容如下

openapi-config.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 的字串標籤,因此可能會導致在變更時驗證過多且在變異時發出不必要的請求。

在這種情況下,仍然建議使用 enhanceEndpoints 在產生的 API 上手動指定標籤,並手動宣告 providesTags/invalidatesTags

程式化用法

src/store/petApi.ts
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 設定檔選項來過濾你的端點。

openapi-config.ts
const filteredConfig: ConfigFile = {
// ...
// should only have endpoints loginUser, placeOrder, getOrderById, deleteOrder
filterEndpoints: ['loginUser', /Order/],
}

端點覆寫

如果一個端點被產生為變異而不是查詢,或者反之亦然,你可以覆寫它

openapi-config.ts
const withOverride: ConfigFile = {
// ...
endpointOverrides: [
{
pattern: 'loginUser',
type: 'mutation',
},
],
}

產生鉤子

設定 hooks: true 將會產生 useQueryuseMutation 鉤子匯出。如果你也想要產生 useLazyQuery 鉤子或更精細的控制,你也可以傳遞一個形狀為 { queries: boolean; lazyQueries: boolean; mutations: boolean } 的物件。

多個輸出檔案

openapi-config.ts
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],
},
},
}