Files
MonkeyCode/ui/src/api/httpClient.ts

220 lines
5.9 KiB
TypeScript
Raw Normal View History

2025-06-25 18:02:45 +08:00
/* eslint-disable */
/* tslint:disable */
// @ts-nocheck
/*
* ---------------------------------------------------------------
* ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API ##
* ## ##
* ## AUTHOR: acacode ##
* ## SOURCE: https://github.com/acacode/swagger-typescript-api ##
* ---------------------------------------------------------------
*/
2025-06-30 17:51:23 +08:00
import { message as Message } from "@c-x/ui";
2025-06-25 18:02:45 +08:00
import type {
AxiosInstance,
AxiosRequestConfig,
HeadersDefaults,
ResponseType,
2025-06-30 17:51:23 +08:00
} from "axios";
import axios from "axios";
2025-06-25 18:02:45 +08:00
export type QueryParamsType = Record<string | number, any>;
export interface FullRequestParams
2025-06-30 17:51:23 +08:00
extends Omit<AxiosRequestConfig, "data" | "params" | "url" | "responseType"> {
2025-06-25 18:02:45 +08:00
/** set parameter to `true` for call `securityWorker` for this request */
secure?: boolean;
/** request path */
path: string;
/** content type of request body */
type?: ContentType;
/** query params */
query?: QueryParamsType;
/** format of response (i.e. response.json() -> format: "json") */
format?: ResponseType;
/** request body */
body?: unknown;
}
export type RequestParams = Omit<
FullRequestParams,
2025-06-30 17:51:23 +08:00
"body" | "method" | "query" | "path"
2025-06-25 18:02:45 +08:00
>;
export interface ApiConfig<SecurityDataType = unknown>
2025-06-30 17:51:23 +08:00
extends Omit<AxiosRequestConfig, "data" | "cancelToken"> {
2025-06-25 18:02:45 +08:00
securityWorker?: (
2025-06-30 17:51:23 +08:00
securityData: SecurityDataType | null,
2025-06-25 18:02:45 +08:00
) => Promise<AxiosRequestConfig | void> | AxiosRequestConfig | void;
secure?: boolean;
format?: ResponseType;
}
export enum ContentType {
2025-06-30 17:51:23 +08:00
Json = "application/json",
FormData = "multipart/form-data",
UrlEncoded = "application/x-www-form-urlencoded",
Text = "text/plain",
2025-06-25 18:02:45 +08:00
}
const redirectToLogin = () => {
const redirectAfterLogin = encodeURIComponent(location.href);
const search = `redirect=${redirectAfterLogin}`;
2025-06-30 17:51:23 +08:00
const pathname = "/login";
2025-06-25 18:02:45 +08:00
window.location.href = `${pathname}?${search}`;
};
type ExtractDataProp<T> = T extends { data?: infer U } ? U : never;
export class HttpClient<SecurityDataType = unknown> {
public instance: AxiosInstance;
private securityData: SecurityDataType | null = null;
2025-06-30 17:51:23 +08:00
private securityWorker?: ApiConfig<SecurityDataType>["securityWorker"];
2025-06-25 18:02:45 +08:00
private secure?: boolean;
private format?: ResponseType;
constructor({
securityWorker,
secure,
format,
...axiosConfig
}: ApiConfig<SecurityDataType> = {}) {
this.instance = axios.create({
withCredentials: true,
...axiosConfig,
2025-06-30 17:51:23 +08:00
baseURL: axiosConfig.baseURL || "",
2025-06-25 18:02:45 +08:00
});
this.secure = secure;
this.format = format;
this.securityWorker = securityWorker;
this.instance.interceptors.response.use(
(resp) => {
if (resp.data.code === 0) {
return resp.data.data;
} else {
Message.error(resp.data.message);
return Promise.reject(resp.data.message);
}
},
(err) => {
if (err?.response?.status === 401) {
2025-06-30 17:51:23 +08:00
Message.error("尚未登录");
2025-06-25 18:02:45 +08:00
redirectToLogin();
return;
}
// 手动取消请求
2025-06-30 17:51:23 +08:00
if (err.code === "ERR_CANCELED") {
2025-06-25 18:02:45 +08:00
return;
}
const msg = err?.response?.data?.message || err?.message;
Message.error(msg);
return Promise.reject(msg);
2025-06-30 17:51:23 +08:00
},
2025-06-25 18:02:45 +08:00
);
}
public setSecurityData = (data: SecurityDataType | null) => {
this.securityData = data;
};
protected mergeRequestParams(
params1: AxiosRequestConfig,
2025-06-30 17:51:23 +08:00
params2?: AxiosRequestConfig,
2025-06-25 18:02:45 +08:00
): AxiosRequestConfig {
const method = params1.method || (params2 && params2.method);
return {
...this.instance.defaults,
...params1,
...(params2 || {}),
headers: {
...((method &&
this.instance.defaults.headers[
method.toLowerCase() as keyof HeadersDefaults
]) ||
{}),
...(params1.headers || {}),
...((params2 && params2.headers) || {}),
},
};
}
protected stringifyFormItem(formItem: unknown) {
2025-06-30 17:51:23 +08:00
if (typeof formItem === "object" && formItem !== null) {
2025-06-25 18:02:45 +08:00
return JSON.stringify(formItem);
} else {
return `${formItem}`;
}
}
protected createFormData(input: Record<string, unknown>): FormData {
return Object.keys(input || {}).reduce((formData, key) => {
const property = input[key];
const propertyContent: any[] =
property instanceof Array ? property : [property];
for (const formItem of propertyContent) {
const isFileType = formItem instanceof Blob || formItem instanceof File;
formData.append(
key,
2025-06-30 17:51:23 +08:00
isFileType ? formItem : this.stringifyFormItem(formItem),
2025-06-25 18:02:45 +08:00
);
}
return formData;
}, new FormData());
}
public request = async <T = any, _E = any>({
secure,
path,
type,
query,
format,
body,
...params
}: FullRequestParams): Promise<ExtractDataProp<T>> => {
const secureParams =
2025-06-30 17:51:23 +08:00
((typeof secure === "boolean" ? secure : this.secure) &&
2025-06-25 18:02:45 +08:00
this.securityWorker &&
(await this.securityWorker(this.securityData))) ||
{};
const requestParams = this.mergeRequestParams(params, secureParams);
const responseFormat = format || this.format || undefined;
if (
type === ContentType.FormData &&
body &&
body !== null &&
2025-06-30 17:51:23 +08:00
typeof body === "object"
2025-06-25 18:02:45 +08:00
) {
body = this.createFormData(body as Record<string, unknown>);
}
if (
type === ContentType.Text &&
body &&
body !== null &&
2025-06-30 17:51:23 +08:00
typeof body !== "string"
2025-06-25 18:02:45 +08:00
) {
body = JSON.stringify(body);
}
return this.instance.request({
...requestParams,
headers: {
...(requestParams.headers || {}),
...(type && type !== ContentType.FormData
2025-06-30 17:51:23 +08:00
? { "Content-Type": type }
2025-06-25 18:02:45 +08:00
: {}),
},
params: query,
responseType: responseFormat,
data: body,
url: path,
});
};
}
2025-06-30 17:51:23 +08:00
export default new HttpClient({ format: "json" }).request;