refactor(frontend): services/api 迁至 src/api,http 迁至 utils/request
对齐 Vue 后台惯例: - src/api/ 域 API(原 services/api) - src/utils/request.ts HTTP 封装(原 services/http.ts) - src/utils/export.ts 客户端导出工具 - src/utils/index.ts 工具统一出口 全局导入改为 @/api 与 @/utils/request,tsc + build 通过。
This commit is contained in:
1 parent
9bf35b369c
commit
d19a03d427
145 files changed
+156
-142
No files matched your search
@@ -0,0 +1,25 @@
|
||||
// 客户端导出工具 — CSV / JSON 下载 // Logan.Li
|
||||
|
||||
export function exportAsCSV(filename: string, data: Record<string, unknown>[]): void {
|
||||
if (data.length === 0) return;
|
||||
const headers = Object.keys(data[0]);
|
||||
const csv = [
|
||||
headers.join(','),
|
||||
...data.map((row) => headers.map((h) => JSON.stringify(row[h] ?? '')).join(',')),
|
||||
].join('\n');
|
||||
const blob = new Blob(['\ufeff' + csv], { type: 'text/csv;charset=utf-8;' });
|
||||
const a = document.createElement('a');
|
||||
a.href = URL.createObjectURL(blob);
|
||||
a.download = filename;
|
||||
a.click();
|
||||
URL.revokeObjectURL(a.href);
|
||||
}
|
||||
|
||||
export function exportAsJSON(filename: string, data: unknown[]): void {
|
||||
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
|
||||
const a = document.createElement('a');
|
||||
a.href = URL.createObjectURL(blob);
|
||||
a.download = filename;
|
||||
a.click();
|
||||
URL.revokeObjectURL(a.href);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// 通用工具出口 — 对齐 Vue 后台惯例(request / export 等) // Logan.Li
|
||||
|
||||
export {
|
||||
http,
|
||||
default as request,
|
||||
getApiBase,
|
||||
buildApiUrl,
|
||||
getWsBase,
|
||||
getAuthToken,
|
||||
type ApiResponse,
|
||||
type ListResponse,
|
||||
} from './request';
|
||||
|
||||
export { exportAsCSV, exportAsJSON } from './export';
|
||||
@@ -0,0 +1,167 @@
|
||||
import { useUserStore } from '@/store';
|
||||
|
||||
const API_PREFIX = '/api/v1';
|
||||
|
||||
// 后端统一响应格式
|
||||
export interface ApiResponse<T = unknown> {
|
||||
code: number;
|
||||
message: string;
|
||||
data: T;
|
||||
}
|
||||
|
||||
// 列表响应格式
|
||||
export interface ListResponse<T = unknown> {
|
||||
list: T[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
type Json = unknown;
|
||||
|
||||
/** 统一 API 根路径,避免 get/post 与 download/upload 行为不一致 // Logan.Li */
|
||||
export function getApiBase(): string {
|
||||
const envBase = import.meta.env.VITE_API_BASE_URL;
|
||||
if (envBase) {
|
||||
const normalized = String(envBase).replace(/\/$/, '');
|
||||
return normalized.endsWith(API_PREFIX) ? normalized : `${normalized}${API_PREFIX}`;
|
||||
}
|
||||
return API_PREFIX;
|
||||
}
|
||||
|
||||
/** 拼接 REST API 完整路径(含 /api/v1 前缀) // Logan.Li */
|
||||
export function buildApiUrl(path: string, params?: URLSearchParams): string {
|
||||
const p = path.startsWith('/') ? path : `/${path}`;
|
||||
let url = `${getApiBase()}${p}`;
|
||||
const qs = params?.toString();
|
||||
if (qs) url += `?${qs}`;
|
||||
return url;
|
||||
}
|
||||
|
||||
function resolveApiUrl(path: string): string {
|
||||
return buildApiUrl(path);
|
||||
}
|
||||
|
||||
/** 获取 WebSocket 根路径(不含 /api/v1) // Logan.Li */
|
||||
export function getWsBase(): string {
|
||||
const envBase = import.meta.env.VITE_API_BASE_URL;
|
||||
if (envBase) {
|
||||
const origin = String(envBase).replace(/\/$/, '').replace(/\/api\/v1$/, '');
|
||||
return origin.replace(/^http/, 'ws');
|
||||
}
|
||||
const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
return `${proto}//${window.location.host}`;
|
||||
}
|
||||
|
||||
export function getAuthToken(): string {
|
||||
return useUserStore.getState().token || localStorage.getItem('token') || '';
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
async function request<T = any>(
|
||||
method: string,
|
||||
url: string,
|
||||
body?: Json,
|
||||
params?: Record<string, string | number | boolean | undefined>,
|
||||
): Promise<T> {
|
||||
let fullUrl = resolveApiUrl(url);
|
||||
if (params) {
|
||||
const searchParams = new URLSearchParams();
|
||||
Object.entries(params).forEach(([key, value]) => {
|
||||
if (value !== undefined && value !== null && value !== '') {
|
||||
searchParams.append(key, String(value));
|
||||
}
|
||||
});
|
||||
const qs = searchParams.toString();
|
||||
if (qs) fullUrl += '?' + qs;
|
||||
}
|
||||
|
||||
const token = getAuthToken();
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
if (token) {
|
||||
headers.Authorization = 'Bearer ' + token;
|
||||
}
|
||||
|
||||
const response = await fetch(fullUrl, {
|
||||
method,
|
||||
headers,
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
|
||||
if (response.status === 401) {
|
||||
useUserStore.getState().logout();
|
||||
window.location.href = '/login';
|
||||
throw new Error('登录已过期,请重新登录');
|
||||
}
|
||||
|
||||
const json: ApiResponse<T> = await response.json();
|
||||
|
||||
if (json.code && json.code !== 200) {
|
||||
throw new Error(json.message || '请求失败');
|
||||
}
|
||||
|
||||
return (json.data !== undefined ? json.data : json) as T;
|
||||
}
|
||||
|
||||
export const http = {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
get: <T = any>(url: string, params?: Record<string, string | number | boolean | undefined>) =>
|
||||
request<T>('GET', url, undefined, params),
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
post: <T = any>(url: string, body?: Json) => request<T>('POST', url, body),
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
put: <T = any>(url: string, body?: Json) => request<T>('PUT', url, body),
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
delete: <T = any>(url: string, body?: Json) => request<T>('DELETE', url, body),
|
||||
|
||||
getRaw: async (url: string): Promise<string> => {
|
||||
const resp = await fetch(resolveApiUrl(url), {
|
||||
headers: { Authorization: 'Bearer ' + getAuthToken() },
|
||||
});
|
||||
if (!resp.ok) throw new Error('HTTP ' + resp.status);
|
||||
return resp.text();
|
||||
},
|
||||
|
||||
putRaw: async (url: string, body: string, contentType: string): Promise<unknown> => {
|
||||
const resp = await fetch(resolveApiUrl(url), {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
Authorization: 'Bearer ' + getAuthToken(),
|
||||
'Content-Type': contentType,
|
||||
},
|
||||
body,
|
||||
});
|
||||
if (!resp.ok) throw new Error('HTTP ' + resp.status);
|
||||
return resp.json();
|
||||
},
|
||||
|
||||
download: async (url: string, filename?: string): Promise<void> => {
|
||||
const resp = await fetch(resolveApiUrl(url), {
|
||||
headers: { Authorization: 'Bearer ' + getAuthToken() },
|
||||
});
|
||||
if (!resp.ok) throw new Error('HTTP ' + resp.status);
|
||||
const blob = await resp.blob();
|
||||
const a = document.createElement('a');
|
||||
a.href = URL.createObjectURL(blob);
|
||||
const disp = resp.headers.get('Content-Disposition') || '';
|
||||
const m = disp.match(/filename="?(.+?)"?$/);
|
||||
a.download = filename || (m ? m[1] : 'download');
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(a.href);
|
||||
},
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
upload: async <T = any>(url: string, formData: FormData): Promise<T> => {
|
||||
const resp = await fetch(resolveApiUrl(url), {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer ' + getAuthToken() },
|
||||
body: formData,
|
||||
});
|
||||
if (!resp.ok) throw new Error('HTTP ' + resp.status);
|
||||
return resp.json();
|
||||
},
|
||||
};
|
||||
|
||||
export default http;
|
||||
Reference in new issue
Block a user