
使用這些基本 REST API 最佳實踐構建出色的 API
客戶端應用程序的開發人員每天與API打交道。根據操作的成功與否或業務邏輯,標準化API響應是一個好習慣。通常,響應包括狀態、錯誤等標準字段。
有了這些標準字段,開發人員可以對操作的狀態做出反應,并構建與應用程序的進一步用戶交互。如果注冊成功,應該關閉表單并顯示成功消息。然而,如果數據格式不正確,驗證錯誤應該在表單中顯示。
這就提出了如何在項目中方便、快速和靈活地描述響應類型的問題。
有時,項目中的響應類型僅用一種類型描述,帶有多個可選參數。在大多數情況下,這可能足夠了,TypeScript在編寫代碼時會建議這些參數,但需要額外檢查這些參數的存在。下面是一個這樣的類型的示例:
export enum ApiStatus {
OK = ok
,
ERROR = error
,
FORM_ERRORS = form_errors
,
REDIRECT = redirect
,
}
export type ApiData = {
status: ApiStatus
error?: string
errors?: Record<string, string>
url?: string
}
這種方法的唯一優點是它的簡單性。我們可以將ApiData類型添加到任何響應類型中,這樣就足夠了。
export type UserProfile = {
id: number
name: string
last_name: string
birthday: string
city: string
}
export type UserProfileResponse = ApiData & {
user: UserProfile
}
// to simulate an API call
const updateProfileAPI = async(data: Partial<UserProfile>): Promise<UserProfileResponse> => {
return Promise.resolve({} as UserProfileResponse)
}
然而,我認為這種單一的優勢被一個顯著的劣勢所抵消。這種方法的缺點是缺乏透明度。
此外,通過向響應類型添加這樣的類型,你永遠無法確切知道特定請求的響應將是什么。想象一下,對于一個POST請求,你可以從API獲得有限數量的響應場景。
場景可能是以下之一:
結果表明,我們不能僅僅通過查看響應類型就了解我們確切的響應選項。要了解所有可能的響應變體,你需要打開執行請求和處理響應的函數的代碼。
上述缺點可以通過自定義實用類型來解決。每個場景都有單獨的類型:成功操作、服務器錯誤、驗證錯誤或強制重定向。
這些類型可以單獨使用或組合使用,以反映特定響應的所有可能響應選項。每種類型都有一個通用類型,允許傳遞對應于該響應的數據類型的數據。
export enum ApiStatus {
OK = ok
,
ERROR = error
,
FORM_ERRORS = form_errors
,
REDIRECT = redirect
,
}
export type ApiSuccess<T extends Record<string, unknown> | unknown = unknown> = T & {
status: ApiStatus.OK,
}
export type ApiError<T extends Record<string, unknown> = { error: string } > = T & {
status: ApiStatus.ERROR,
}
export type ApiFormErrors<T extends Record<string, unknown> = { errors: Record<string, string> }> = T & {
status: ApiStatus.FORM_ERRORS,
}
export type ApiRedirect<T extends Record<string, unknown> = { url: string }> = T & {
status: ApiStatus.REDIRECT,
}
export type ApiResponse<T extends Record<string, unknown> | unknown = unknown, K extends Record<string, unknown> = { error: string }, R extends Record<string, unknown> = { errors: Record<string, string> }> = ApiSuccess<T> | ApiError<K> | ApiFormErrors<R>
此外,我還創建了一個通用的ApiResponse
類型,它包括幾個實用類型。這將節省為每個POST請求添加所有場景的時間。
以下是針對不同場景使用這些實用類型的示例:
export type FetchUserProfile = ApiSuccess<{
user: UserProfile
}>
export type FetchUserConfig = ApiSuccess<{
config: Record<string, string | number | boolean>
}> | ApiError
export type AddUserSocialNetworkAsLoginMethod = ApiResponse<{
social_network: string,
is_active: boolean
}, { message: string }> | ApiRedirect<{ redirect_url: string }>
下面是一個用戶個人資料的類型示例,以及用戶個人資料更新功能返回的響應類型。
const updateProfile = async(): Promise<void> => {
try {
const data = await updateProfileAPI({ name: 'New name' })
// [!!!] Typescript does not highlight that the 'user' property could not exist on the 'data' property
// In the case when data.status === ApiStatus.ERROR|FORM_ERRORS|REDIRECT
console.log(data.user.id)
if (data.status === ApiStatus.OK) {
updatedProfileState(data.user)
return
}
if (data.status === ApiStatus.ERROR) {
// Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
// Type 'undefined' is not assignable to type 'string'.
showNotification('danger', data.error)
return
}
if (data.status === ApiStatus.FORM_ERRORS) {
// Argument of type 'Record<string, string> | undefined' is not assignable to parameter of type 'Record<string, string>'.
// Type 'undefined' is not assignable to type 'Record<string, string>'.
showValidationErrors(data.errors)
return
}
if (data.status === ApiStatus.REDIRECT) {
// Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
// Type 'undefined' is not assignable to type 'string'.
redirect(data.url)
return
}
throw new Error('Something went wrong...')
} catch (err) {
console.error('User: updateProfile - ', err)
}
}
這是一張TypeScript如何檢查這段代碼的圖片:
在圖片中,你可以看到TypeScript突出顯示了一些標準響應的預期值,如error、errors或url。這是因為linter(代碼檢查器)認為這些值可能是未定義的。這個問題可以通過在狀態檢查時增加額外的檢查來輕松解決,但它已經展示了這種方法的問題。
另外,請注意,在console.log(data.user.id)這一行中,user值沒有被突出顯示為可能未定義。如果我們收到的響應類型不是成功的,這是我們會遇到的情況。
使用ApiResponse等實用類型,我們就不會遇到這樣的問題。
export type UserProfileResponseV2 = ApiResponse<{
user: UserProfile
}> | ApiRedirect
const newUpdateProfileAPI = async(data: Partial<UserProfile>): Promise<UserProfileResponseV2> => {
return Promise.resolve({} as UserProfileResponseV2)
}
這是一張展示TypeScript如何對這段代碼進行lint檢查的圖片:
在這種情況下,一切工作正常進行:
TypeScript理解對于相應的狀態,將會有相應的標準字段。
它指出,在除了成功的響應之外的所有響應類型中,user值可能是未定義的。然而,在檢查響應的成功狀態后,這個值不再被突出顯示,并且是已定義的。
在項目中實現這些實用類型后,開發人員體驗顯著提升。現在,類型完全對應于API可以提供的可能響應場景。
這也有助于避免在某些響應類型中不可用值的使用潛在錯誤,就像user值的例子一樣。
此外,不需要查看代碼中的響應處理實現就能理解實際的響應類型。你可以立即看到完整的情況。
如果你對這些實用類型是如何工作的感興趣,你可以查看TypeScript Playground頁面。
冪簡集成是國內領先的API集成管理平臺,專注于為開發者提供全面、高效、易用的API集成解決方案。冪簡API平臺可以通過以下兩種方式找到所需API:通過關鍵詞搜索API、或者從API Hub分類頁進入尋找。
原文鏈接:https://itnext.io/how-to-write-api-response-types-with-typescript-f8152ddd43dd