refactor(webui): extract ApiClient + lift OneBotInstance config editor

App.tsx was the single source of truth for token, fetch policy, 401
handling, and per-UIN config edit state — fetchApi was drilled into
every page and LogsPage read localStorage directly to build its SSE
URL, giving two parallel truths for the bearer token.

Promote the closure to a deep ApiClient module (domain methods +
request() escape hatch) injected via ApiProvider/useApi, and lift
selectedUin/config/saveStatus into useOneBotInstanceConfig so
ConfigPage is self-contained. normalizeOneBotConfig becomes a pure
function. ConfigPage now guards UIN switches when the editor is
dirty and refetches the server-normalised config after save.

ConfigPage prop count drops from 7 to 1; App.tsx from 421 to 270 LOC.
This commit is contained in:
DrSmoothl committed 2026-05-16 02:04:11 +08:00
1 parent 47921eee12
commit b89d51d984
11 files changed
+818 -398

No files matched your search

+251
View File
@@ -0,0 +1,251 @@
import type { HookProcessInfo, LogEntry, QQInfo, SystemInfo } from '@/types';
import type { PasswordRule } from '@/components/pages/change-password-page';
import { normalizeOneBotConfig } from '@/lib/onebot-config';
import {
ApiError,
type ApiClient,
type ChangePasswordResult,
type CreateApiClientOptions,
type LoginResult,
type LogsStreamOptions,
type ProcessActionResult,
type TokenStore,
} from './types';
import { localStorageTokenStore } from './token-store';
const DEFAULT_TOKEN_KEY = 'snowluma_token';
interface ErrorPayload {
message?: string;
error?: string;
code?: string;
}
async function readJson<T>(res: Response): Promise<T> {
try {
return (await res.json()) as T;
} catch {
return {} as T;
}
}
function extractErrorMessage(payload: ErrorPayload, fallback: string): string {
return payload.message || payload.error || fallback;
}
class HttpApiClient implements ApiClient {
private tokenStore: TokenStore;
private currentToken: string | null;
private onUnauthorized?: () => void;
// namespaced surfaces are bound up-front so callers can destructure
readonly processes: ApiClient['processes'];
readonly config: ApiClient['config'];
readonly logs: ApiClient['logs'];
constructor(opts: CreateApiClientOptions = {}) {
this.tokenStore = opts.tokenStore ?? localStorageTokenStore(DEFAULT_TOKEN_KEY);
this.currentToken = this.tokenStore.load();
this.onUnauthorized = opts.onUnauthorized;
this.processes = {
list: () => this.getJson<{ list: HookProcessInfo[] }>('/api/processes').then((d) => d.list ?? []),
load: (pid) => this.postJson<ProcessActionResult>(`/api/processes/${pid}/load`),
unload: (pid) => this.postJson<ProcessActionResult>(`/api/processes/${pid}/unload`),
refresh: (pid) => this.postJson<ProcessActionResult>(`/api/processes/${pid}/refresh`),
};
this.config = {
get: async (uin) => {
const url = `/api/config/${encodeURIComponent(uin)}`;
const data = await this.getJson<{ config?: unknown } | unknown>(url);
const raw =
typeof data === 'object' && data != null && 'config' in (data as Record<string, unknown>)
? (data as { config: unknown }).config
: data;
return normalizeOneBotConfig(raw);
},
save: async (uin, config) => {
const url = `/api/config/${encodeURIComponent(uin)}`;
const data = await this.fetchJson<{ config?: unknown } | unknown>(url, {
method: 'POST',
body: JSON.stringify(config),
});
const raw =
typeof data === 'object' && data != null && 'config' in (data as Record<string, unknown>)
? (data as { config: unknown }).config
: data;
return normalizeOneBotConfig(raw);
},
};
this.logs = {
list: async (limit = 500) => {
const data = await this.getJson<{ list: LogEntry[] }>(`/api/logs?limit=${limit}`);
return data.list ?? [];
},
stream: (options) => this.openLogStream(options),
};
}
// ---------- HTTP helpers ----------
async request(url: string, init: RequestInit = {}): Promise<Response> {
const headers: Record<string, string> = {
...((init.headers as Record<string, string> | undefined) ?? {}),
};
if (this.currentToken) headers['Authorization'] = `Bearer ${this.currentToken}`;
if (init.body && !headers['Content-Type']) headers['Content-Type'] = 'application/json';
const res = await fetch(url, { ...init, headers });
if (res.status === 401) {
this.setToken(null);
this.onUnauthorized?.();
}
return res;
}
/** Like request(), but throws ApiError on non-2xx and parses JSON. */
private async fetchJson<T>(url: string, init: RequestInit = {}): Promise<T> {
const res = await this.request(url, init);
if (!res.ok) {
const payload = await readJson<ErrorPayload>(res);
throw new ApiError(res.status, extractErrorMessage(payload, res.statusText || '请求失败'), payload.code);
}
return readJson<T>(res);
}
private getJson<T>(url: string): Promise<T> {
return this.fetchJson<T>(url);
}
private postJson<T>(url: string, body?: unknown): Promise<T> {
return this.fetchJson<T>(url, {
method: 'POST',
body: body == null ? undefined : JSON.stringify(body),
});
}
// ---------- token management ----------
private setToken(token: string | null): void {
this.currentToken = token;
this.tokenStore.save(token);
}
// ---------- auth ----------
async login(password: string): Promise<LoginResult> {
// Login deliberately bypasses fetchJson/onUnauthorized so a bad password
// doesn't trigger a global sign-out side effect.
try {
const res = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password }),
});
if (!res.ok) {
const payload = await readJson<ErrorPayload>(res);
return { ok: false, message: extractErrorMessage(payload, '令牌错误') };
}
const payload = await readJson<{ token: string; mustChangePassword?: boolean }>(res);
this.setToken(payload.token);
return { ok: true, mustChangePassword: !!payload.mustChangePassword };
} catch (e) {
return { ok: false, message: e instanceof Error ? e.message : '网络错误' };
}
}
async logout(): Promise<void> {
try {
await this.request('/api/logout', { method: 'POST' });
} catch {
/* ignore */
}
this.setToken(null);
}
async status(): Promise<boolean> {
if (!this.currentToken) return false;
try {
const res = await this.request('/api/status');
return res.ok;
} catch {
return false;
}
}
async mustChangePassword(): Promise<boolean> {
try {
const data = await this.getJson<{ mustChangePassword?: boolean }>('/api/auth/state');
return !!data.mustChangePassword;
} catch {
return false;
}
}
async checkPasswordStrength(password: string): Promise<{ rules: PasswordRule[]; valid: boolean }> {
try {
const data = await this.postJson<{ rules?: PasswordRule[]; valid?: boolean }>(
'/api/auth/check-strength',
{ password },
);
return { rules: data.rules ?? [], valid: !!data.valid };
} catch {
return { rules: [], valid: false };
}
}
async changePassword(oldPassword: string, newPassword: string): Promise<ChangePasswordResult> {
try {
const data = await this.postJson<{ success?: boolean; message?: string }>(
'/api/auth/change-password',
{ oldPassword, newPassword },
);
return { success: !!data.success, message: data.message };
} catch (e) {
if (e instanceof ApiError) return { success: false, message: e.message };
return { success: false, message: e instanceof Error ? e.message : '网络错误' };
}
}
// ---------- top-level resources ----------
async qqList(): Promise<QQInfo[]> {
const data = await this.getJson<{ list: QQInfo[] }>('/api/qq-list');
return data.list ?? [];
}
system(): Promise<SystemInfo> {
return this.getJson<SystemInfo>('/api/system');
}
// ---------- SSE ----------
private openLogStream(options: LogsStreamOptions): () => void {
if (!this.currentToken) {
options.onStatus?.('closed');
return () => {};
}
const url = `/api/logs/stream?token=${encodeURIComponent(this.currentToken)}`;
const source = new EventSource(url);
source.onopen = () => options.onStatus?.('open');
source.onerror = () => options.onStatus?.('reconnecting');
source.onmessage = (event) => {
try {
const parsed = JSON.parse(event.data) as LogEntry | { type: string };
if ('type' in parsed) return; // control frame, not a log line
options.onLine(parsed);
} catch {
/* malformed frame, skip */
}
};
return () => {
source.close();
options.onStatus?.('closed');
};
}
}
export function createApiClient(options: CreateApiClientOptions = {}): ApiClient {
return new HttpApiClient(options);
}
+14
View File
@@ -0,0 +1,14 @@
import { createContext, useContext, type ReactNode } from 'react';
import type { ApiClient } from './types';
const ApiContext = createContext<ApiClient | null>(null);
export function ApiProvider({ client, children }: { client: ApiClient; children: ReactNode }) {
return <ApiContext.Provider value={client}>{children}</ApiContext.Provider>;
}
export function useApi(): ApiClient {
const client = useContext(ApiContext);
if (!client) throw new Error('useApi must be used inside <ApiProvider>');
return client;
}
+13
View File
@@ -0,0 +1,13 @@
export { createApiClient } from './client';
export { ApiProvider, useApi } from './context';
export { ApiError } from './types';
export type {
ApiClient,
ChangePasswordResult,
CreateApiClientOptions,
LoginResult,
LogsStreamOptions,
ProcessActionResult,
StreamStatus,
TokenStore,
} from './types';
+11
View File
@@ -0,0 +1,11 @@
import type { TokenStore } from './types';
export function localStorageTokenStore(key: string): TokenStore {
return {
load: () => localStorage.getItem(key),
save: (token) => {
if (token == null) localStorage.removeItem(key);
else localStorage.setItem(key, token);
},
};
}
+88
View File
@@ -0,0 +1,88 @@
import type {
HookProcessInfo,
LogEntry,
OneBotConfig,
QQInfo,
SystemInfo,
} from '@/types';
import type { PasswordRule } from '@/components/pages/change-password-page';
export class ApiError extends Error {
status: number;
code: string | undefined;
constructor(status: number, message: string, code?: string) {
super(message);
this.name = 'ApiError';
this.status = status;
this.code = code;
}
}
export type LoginResult =
| { ok: true; mustChangePassword: boolean }
| { ok: false; message: string };
export type ChangePasswordResult = { success: boolean; message?: string };
export type ProcessActionResult = {
process?: HookProcessInfo & { error?: string };
};
export type StreamStatus = 'open' | 'reconnecting' | 'closed';
export interface LogsStreamOptions {
onLine: (line: LogEntry) => void;
onStatus?: (status: StreamStatus) => void;
}
export interface ApiClient {
// ---- auth ----
login(password: string): Promise<LoginResult>;
logout(): Promise<void>;
/** True if the current token is still valid. */
status(): Promise<boolean>;
/** Whether the current session must rotate its password before doing anything else. */
mustChangePassword(): Promise<boolean>;
checkPasswordStrength(password: string): Promise<{ rules: PasswordRule[]; valid: boolean }>;
changePassword(oldPassword: string, newPassword: string): Promise<ChangePasswordResult>;
// ---- system ----
qqList(): Promise<QQInfo[]>;
system(): Promise<SystemInfo>;
// ---- hook processes ----
processes: {
list(): Promise<HookProcessInfo[]>;
load(pid: number): Promise<ProcessActionResult>;
unload(pid: number): Promise<ProcessActionResult>;
refresh(pid: number): Promise<ProcessActionResult>;
};
// ---- OneBotInstance per-UIN config ----
config: {
get(uin: string): Promise<OneBotConfig>;
save(uin: string, config: OneBotConfig): Promise<OneBotConfig>;
};
// ---- logs ----
logs: {
list(limit?: number): Promise<LogEntry[]>;
/** Subscribe to the SSE log stream. Returns a disposer. */
stream(options: LogsStreamOptions): () => void;
};
/** Escape hatch for endpoints not yet wrapped above. */
request(url: string, init?: RequestInit): Promise<Response>;
}
export interface TokenStore {
load(): string | null;
save(token: string | null): void;
}
export interface CreateApiClientOptions {
/** Persists the bearer token across reloads. Defaults to localStorage('snowluma_token'). */
tokenStore?: TokenStore;
/** Fires whenever a request returns 401, after the token has been cleared. */
onUnauthorized?: () => void;
}