UNPKG

@shixinde/apifox-swagger

Version:

从 Apifox 导出 Swagger/OpenAPI 文档并生成 TypeScript 类型定义的工具

83 lines (82 loc) 2.83 kB
/** * OpenAPI 基础类型定义 * 用于类型安全的 API 调用 */ export type HttpMethod = 'get' | 'post' | 'put' | 'delete' | 'patch' | 'head' | 'options'; export type PathParams<T extends string> = T extends `${infer _Start}{${infer Param}}${infer Rest}` ? { [K in Param]: string | number; } & PathParams<Rest> : {}; export type QueryParams = Record<string, string | number | boolean | undefined>; export type RequestBody = Record<string, any> | FormData | string | undefined; export interface ApiResponse<T = any> { data: T; status: number; statusText: string; headers: Record<string, string>; } export interface ApiError { message: string; status?: number; code?: string; } export interface PathConfig<TPath extends string = string, TMethod extends HttpMethod = HttpMethod, TParams = any, TQuery = any, TBody = any, TResponse = any> { path: TPath; method: TMethod; params?: TParams; query?: TQuery; body?: TBody; response?: TResponse; } export type InferMethodFromPaths<T> = T extends keyof any ? T extends string ? HttpMethod : never : never; export type InferParamsFromPath<T extends string> = PathParams<T>; export interface ApiEndpoint<TPath extends string, TMethod extends HttpMethod, TParams = {}, TQuery = {}, TBody = undefined, TResponse = any> { path: TPath; method: TMethod; params?: TParams; query?: TQuery; body?: TBody; response: TResponse; } export type Paths = Record<string, any>; export type ExtractPaths<T extends Paths> = keyof T; export type ExtractMethods<T extends Paths, P extends keyof T> = keyof T[P] & HttpMethod; export type ExtractPathParams<T extends Paths, P extends keyof T, M extends keyof T[P]> = T[P][M] extends { parameters?: { path?: infer PathParams; }; } ? PathParams : {}; export type ExtractQueryParams<T extends Paths, P extends keyof T, M extends keyof T[P]> = T[P][M] extends { parameters?: { query?: infer QueryParams; }; } ? QueryParams : {}; export type ExtractRequestBody<T extends Paths, P extends keyof T, M extends keyof T[P]> = T[P][M] extends { requestBody?: { content?: { 'application/json'?: infer Body; }; }; } ? Body : T[P][M] extends { requestBody?: { content?: { 'multipart/form-data'?: infer Body; }; }; } ? Body : undefined; export type ExtractResponse<T extends Paths, P extends keyof T, M extends keyof T[P]> = T[P][M] extends { responses?: { 200?: { content?: { 'application/json'?: infer Response; }; }; }; } ? Response : T[P][M] extends { responses?: { 201?: { content?: { 'application/json'?: infer Response; }; }; }; } ? Response : any;