Files
erp_sb/electron-vue-template/src/renderer/api/http.ts
悠山 02858146b3 style(components): format CSS styles in Vue components
- Remove extra spaces in CSS property declarations
- Consolidate multi-line CSS rules into single lines
- Maintain consistent formatting across component styles
- Improve readability by removing unnecessary line breaks
- Ensure uniform styling structure in scoped CSS blocks
2025-11-28 17:14:00 +08:00

140 lines
4.0 KiB
TypeScript

import { AppConfig, isRuoyiPath } from '../config'
export type HttpMethod = 'GET' | 'POST' | 'DELETE'
export const CONFIG = AppConfig
function resolveBase(path: string): string {
return isRuoyiPath(path) ? CONFIG.RUOYI_BASE : CONFIG.CLIENT_BASE
}
function buildQuery(params?: Record<string, unknown>): string {
if (!params) return '';
const query = new URLSearchParams();
Object.entries(params).forEach(([key, value]) => {
if (value != null) query.append(key, String(value));
});
return query.toString() ? `?${query}` : '';
}
async function getToken(): Promise<string> {
try {
const tokenModule = await import('../utils/token');
return tokenModule.getToken() || '';
} catch {
return '';
}
}
async function getUsername(): Promise<string> {
try {
const tokenModule = await import('../utils/token');
return tokenModule.getUsernameFromToken() || '';
} catch {
return '';
}
}
async function request<T>(path: string, options: RequestInit & { signal?: AbortSignal }): Promise<T> {
const token = await getToken();
const username = await getUsername();
let res: Response;
try {
res = await fetch(`${resolveBase(path)}${path}`, {
credentials: 'omit',
cache: 'no-store',
...options,
headers: {
'Content-Type': 'application/json;charset=UTF-8',
...(token ? { 'Authorization': `Bearer ${token}` } : {}),
...(username ? { 'username': username } : {}),
...options.headers
}
});
} catch (e) {
throw new Error('无法连接服务器,请检查网络后重试');
}
if (!res.ok) {
if (res.status >= 500) {
throw new Error('无法连接服务器,请检查网络后重试');
}
const text = await res.text().catch(() => '');
throw new Error(text || '无法连接服务器,请检查网络后重试');
}
const contentType = res.headers.get('content-type') || '';
if (contentType.includes('application/json')) {
const json: any = await res.json();
if (json.code !== undefined && json.code !== 0 && json.code !== 200) {
const error: any = new Error(json.msg || '请求失败');
error.code = json.code;
throw error;
}
return json as T;
}
return (await res.text()) as unknown as T;
}
export const http = {
get<T>(path: string, params?: Record<string, unknown>, signal?: AbortSignal) {
return request<T>(`${path}${buildQuery(params)}`, { method: 'GET', signal });
},
post<T>(path: string, body?: unknown, signal?: AbortSignal) {
return request<T>(path, {
method: 'POST',
body: body ? JSON.stringify(body) : undefined,
signal
});
},
delete<T>(path: string) {
return request<T>(path, { method: 'DELETE' });
},
async upload<T>(path: string, form: FormData, signal?: AbortSignal) {
const token = await getToken();
const username = await getUsername();
let res: Response;
try {
res = await fetch(`${resolveBase(path)}${path}`, {
method: 'POST',
body: form,
credentials: 'omit',
cache: 'no-store',
headers: {
...(token ? { 'Authorization': `Bearer ${token}` } : {}),
...(username ? { 'username': username } : {})
},
signal
});
} catch (e) {
throw new Error('无法连接服务器,请检查网络后重试');
}
if (!res.ok) {
if (res.status >= 500) {
throw new Error('无法连接服务器,请检查网络后重试');
}
const text = await res.text().catch(() => '');
throw new Error(text || '无法连接服务器,请检查网络后重试');
}
const contentType = res.headers.get('content-type') || '';
if (contentType.includes('application/json')) {
const json: any = await res.json();
if (json.code !== undefined && json.code !== 0 && json.code !== 200) {
const error: any = new Error(json.msg || '请求失败');
error.code = json.code;
throw error;
}
return json as T;
}
return (await res.text()) as unknown as T;
}
};