mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 11:49:19 +08:00
refacor: 重构目录架构
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
import { loadConfig, resolveApiUrl, resolveToken } from '../config.js';
|
||||
import { runSpinner } from '../ui/render.js';
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public status?: number,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
async function parseError(res: Response): Promise<string> {
|
||||
try {
|
||||
const body = await res.json();
|
||||
if (typeof body?.message === 'string') return body.message;
|
||||
if (Array.isArray(body?.message)) return body.message.join(', ');
|
||||
return JSON.stringify(body);
|
||||
} catch {
|
||||
return res.statusText || `HTTP ${res.status}`;
|
||||
}
|
||||
}
|
||||
|
||||
export async function apiRequest<T>(
|
||||
method: string,
|
||||
path: string,
|
||||
body?: unknown,
|
||||
auth = true,
|
||||
): Promise<T> {
|
||||
const config = await loadConfig();
|
||||
const baseUrl = resolveApiUrl(undefined, config);
|
||||
const token = resolveToken(undefined, config);
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
};
|
||||
if (auth && token) {
|
||||
headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
const doFetch = async () => {
|
||||
const res = await fetch(`${baseUrl}/api${path}`, {
|
||||
method,
|
||||
headers,
|
||||
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new ApiError(await parseError(res), res.status);
|
||||
}
|
||||
if (res.status === 204) return undefined as T;
|
||||
const contentType = res.headers.get('content-type') || '';
|
||||
if (contentType.includes('application/json')) {
|
||||
return (await res.json()) as T;
|
||||
}
|
||||
return (await res.text()) as T;
|
||||
};
|
||||
|
||||
return runSpinner(doFetch, '请求中...');
|
||||
}
|
||||
|
||||
export async function apiDownload(path: string, outfile: string): Promise<string> {
|
||||
const config = await loadConfig();
|
||||
const baseUrl = resolveApiUrl(undefined, config);
|
||||
const token = resolveToken(undefined, config);
|
||||
|
||||
const doFetch = async () => {
|
||||
const res = await fetch(`${baseUrl}/api${path}`, {
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
||||
});
|
||||
if (!res.ok) throw new ApiError(await parseError(res), res.status);
|
||||
const { writeFile } = await import('fs/promises');
|
||||
const text = await res.text();
|
||||
await writeFile(outfile, text, 'utf8');
|
||||
return outfile;
|
||||
};
|
||||
|
||||
return runSpinner(doFetch, '正在下载...');
|
||||
}
|
||||
Reference in New Issue
Block a user