Files
pika/web/admin/src/api/request.ts
T
dushixiang 1af64eccd9 refactor: simplify theme system to filesystem-only with self-contained portal
主题系统从带数据库/事务/repo 层/远程下载/配置管理/主题市场的重型架构,
彻底简化为纯文件系统操作:

后端:
- 主题数据全部存放在 data/themes/ 目录,不经过数据库
- 删除主题配置功能(managed/raw/redirect schema、配置存取 API、
  ThemeConfiguration model、theme_configurations 表、repo 层)
- 删除远程下载(URL 安装、GitHub Release 更新、SSRF 防护、SHA-256)
- 删除版本范围检查(semver 解析/比较/匹配、pikaVersion 校验)
- 删除主题市场
- ThemeService 不再持有 db,合并为 theme.go + theme_util.go 两个文件
- 主题类型从 models 包移到 service 包(非数据库模型)
- 保留:ZIP 上传解压(含目录穿越防护)、目录扫描列表、启用/删除、
  覆盖安装、默认主题回退、启动恢复、入口 HTML 渲染缓存

前端 portal(官方默认主题):
- 从 47 个碎片文件精简到 15 个,按标准目录组织
- 删除 theme-sdk 包,API 客户端和类型内联回 portal,完全自包含
- 按职责拆分:types.ts / api.ts / constants.ts / lib/utils.ts /
  contexts/ColorMode.tsx / hooks/index.ts / components.tsx / pages/
- 每个页面一个文件,图表和子组件内联,fork 二开只需看一个文件
2026-08-09 22:45:43 +08:00

185 lines
5.0 KiB
TypeScript

const BASE_URL = '/api';
const DEFAULT_TIMEOUT = 30000;
export interface RequestConfig extends RequestInit {
timeout?: number;
}
export interface HttpResponse<T = unknown> {
data: T;
status: number;
statusText: string;
headers: Record<string, string>;
url: string;
}
class HttpError extends Error {
response?: {
status: number;
statusText: string;
data?: unknown;
};
constructor(message: string, response?: HttpError['response']) {
super(message);
this.name = 'HttpError';
this.response = response;
}
}
const parseResponseData = async (response: Response) => {
const contentType = response.headers.get('content-type') || '';
if (response.status === 204) {
return undefined;
}
if (contentType.includes('application/json')) {
try {
return await response.json();
} catch (error) {
console.warn('解析 JSON 响应失败', error);
return undefined;
}
}
return response.text();
};
const headersToRecord = (headers: Headers) => {
const record: Record<string, string> = {};
headers.forEach((value, key) => {
record[key] = value;
});
return record;
};
const sendRequest = async <T>(url: string, config: RequestConfig = {}): Promise<HttpResponse<T>> => {
const {timeout = DEFAULT_TIMEOUT, headers, body, ...restConfig} = config;
const controller = new AbortController();
const timer = window.setTimeout(() => controller.abort(), timeout);
try {
const token = localStorage.getItem('token');
const finalHeaders = new Headers(headers || {});
if (token) {
finalHeaders.set('Authorization', `Bearer ${token}`);
}
const hasBody = body !== undefined && body !== null;
const isFormData = typeof FormData !== 'undefined' && body instanceof FormData;
if (hasBody && !isFormData && !finalHeaders.has('Content-Type')) {
finalHeaders.set('Content-Type', 'application/json');
}
const response = await fetch(`${BASE_URL}${url}`, {
...restConfig,
body,
headers: finalHeaders,
signal: controller.signal,
});
const data = await parseResponseData(response);
if (response.status === 401) {
localStorage.removeItem('token');
localStorage.removeItem('userInfo');
if (window.location.pathname.startsWith('/admin')) {
window.location.href = '/admin/login';
}
throw new HttpError('未认证或认证已过期', {
status: response.status,
statusText: response.statusText,
data,
});
}
if (!response.ok) {
const message =
typeof data === 'object' && data !== null && 'message' in data
? (data as { message?: string }).message
: undefined;
throw new HttpError(message || '请求失败,请稍后重试', {
status: response.status,
statusText: response.statusText,
data,
});
}
return {
data: data as T,
status: response.status,
statusText: response.statusText,
headers: headersToRecord(response.headers),
url: response.url,
};
} catch (error) {
if (error instanceof DOMException && error.name === 'AbortError') {
throw new Error('请求超时');
}
throw error;
} finally {
clearTimeout(timer);
}
};
const normalizeBody = (data?: any) => {
if (data === undefined || data === null) {
return undefined;
}
const isForm =
(typeof FormData !== 'undefined' && data instanceof FormData) ||
(typeof Blob !== 'undefined' && data instanceof Blob) ||
(typeof URLSearchParams !== 'undefined' && data instanceof URLSearchParams);
if (isForm) {
return data;
}
if (typeof data === 'string') {
return data;
}
return JSON.stringify(data);
};
export interface ApiResponse<T = any> {
code?: number;
message?: string;
data?: T;
}
export const get = <T = any>(url: string, config?: RequestConfig) => {
return sendRequest<T>(url, {
...(config || {}),
method: 'GET',
});
};
export const post = <T = any>(url: string, data?: any, config?: RequestConfig) => {
return sendRequest<T>(url, {
...(config || {}),
method: 'POST',
body: normalizeBody(data),
});
};
export const put = <T = any>(url: string, data?: any, config?: RequestConfig) => {
return sendRequest<T>(url, {
...(config || {}),
method: 'PUT',
body: normalizeBody(data),
});
};
export const del = <T = any>(url: string, config?: RequestConfig) => {
return sendRequest<T>(url, {
...(config || {}),
method: 'DELETE',
});
};
const request = {
get,
post,
put,
delete: del,
};
export default request;