Files
tangzhuan-yu/frontend/lib/request.ts
T

145 lines
5.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import axios, { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
const request: AxiosInstance = axios.create({
baseURL: '',
timeout: 30000,
headers: {
'Content-Type': 'application/json',
},
});
request.interceptors.request.use(
(config) => {
const token = localStorage.getItem('auth_token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
// 实例上默认写死了 application/json,发 FormData 时必须去掉,
// 否则表单会被当成 JSON 发送,后端 Form(...) 解析不到字段而返回 422。
// 删掉后 axios 会自动补上带 boundary 的 multipart/form-data。
if (typeof FormData !== 'undefined' && config.data instanceof FormData) {
delete config.headers['Content-Type'];
}
return config;
},
(error) => Promise.reject(error),
);
const FIELD_LABELS: Record<string, string> = {
title: '标题',
desc: '描述',
price: '价格',
post_price: '运费',
quantity: '数量',
cookie_id: '账号',
item_id: '商品',
images: '图片',
};
/** 闲鱼常见的业务错误码 → 人话。放在前端兜底,后端也会做一次。 */
const BIZ_HINTS: Array<[RegExp, string]> = [
[/FAIL_BIZ_TITLE_LENGTH_TOO_LONG|标题不能超过\s*30/i, '标题不能超过 30 个字'],
[/FAIL_BIZ_JSON_ERROR|RGV587|挤爆|USER_VALIDATE/i, '闲鱼风控拦截,发布已暂停 10 分钟,请到时再试'],
[/FAIL_BIZ_DESC/i, '商品描述不符合闲鱼要求,请精简后重试'],
[/SESSION_EXPIRED|FAIL_SYS_SESSION_EXPIRED|令牌/i, '闲鱼登录态已失效,请重新扫码登录该账号'],
];
/** 把 FastAPI/Pydantic 的 detail(字符串或数组)翻成一句中文原因。 */
function detailToMessage(detail: unknown): string | null {
if (typeof detail === 'string' && detail.trim()) {
for (const [pattern, hint] of BIZ_HINTS) {
if (pattern.test(detail)) return hint;
}
return detail;
}
if (!Array.isArray(detail) || detail.length === 0) return null;
const parts = detail.map((entry) => {
const item = entry as { loc?: unknown[]; msg?: string; type?: string };
const loc = Array.isArray(item.loc) ? item.loc.filter((key) => key !== 'body' && key !== 'query') : [];
const field = loc.length ? String(loc[loc.length - 1]) : '';
const label = FIELD_LABELS[field] || field || '请求参数';
const msg = String(item.msg || '');
const max = msg.match(/at most (\d+) characters/);
if (max) return `${label}最多 ${max[1]} 个字符(当前 ${(item as { input?: unknown }).input ? String((item as { input?: unknown }).input).length : '?'} 个)`;
const min = msg.match(/at least (\d+) characters?/);
if (min) return `${label}至少 ${min[1]} 个字符`;
if (/greater than 0/.test(msg)) return `${label}必须大于 0`;
if (/greater than or equal to 0/.test(msg)) return `${label}不能为负数`;
if (/valid number/.test(msg)) return `${label}必须是数字`;
if (/valid integer|integer/i.test(msg)) return `${label}必须是整数`;
if (/field required|missing/i.test(item.type || msg)) return `缺少${label}`;
return msg ? `${label}:${msg}` : `${label}不合法`;
});
return parts.join(';');
}
request.interceptors.response.use(
(response: AxiosResponse) => response,
(error: AxiosError) => {
if (error.response?.status === 401) {
localStorage.removeItem('auth_token');
try {
window.dispatchEvent(new Event('auth:logout'));
} catch {
/* no-op (SSR) */
}
}
// 把后端的可读原因提到 message 上:默认 axios 只会说
// "Request failed with status code 422",用户看不到到底哪个字段不合法。
const readable = detailToMessage((error.response?.data as { detail?: unknown } | undefined)?.detail);
if (readable) {
const wrapped = new Error(readable) as Error & { status?: number; data?: unknown };
wrapped.status = error.response?.status;
wrapped.data = error.response?.data;
return Promise.reject(wrapped);
}
return Promise.reject(error);
},
);
export const get = async <T = unknown>(
url: string,
params?: Record<string, any>,
config?: AxiosRequestConfig,
): Promise<T> => {
const response = await request.get<T>(url, { params, ...config });
return response.data;
};
export const post = async <T = unknown>(
url: string,
data?: unknown,
config?: AxiosRequestConfig,
): Promise<T> => {
const response = await request.post<T>(url, data, config);
return response.data;
};
export const put = async <T = unknown>(
url: string,
data?: unknown,
config?: AxiosRequestConfig,
): Promise<T> => {
const response = await request.put<T>(url, data, config);
return response.data;
};
export const patch = async <T = unknown>(
url: string,
data?: unknown,
config?: AxiosRequestConfig,
): Promise<T> => {
const response = await request.patch<T>(url, data, config);
return response.data;
};
export const del = async <T = unknown>(
url: string,
config?: AxiosRequestConfig,
): Promise<T> => {
const response = await request.delete<T>(url, config);
return response.data;
};
export default request;