feat:简单添加管理员后台功能
This commit is contained in:
62
client/src/lib/api.ts
Normal file
62
client/src/lib/api.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import { getToken, clearAuth } from './adminAuth';
|
||||
|
||||
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000';
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
|
||||
constructor(message: string, status: number) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const token = getToken();
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
const res = await fetch(`${API_BASE_URL}${path}`, {
|
||||
...init,
|
||||
headers: {
|
||||
...headers,
|
||||
...(init?.headers || {}),
|
||||
},
|
||||
credentials: 'include',
|
||||
});
|
||||
|
||||
if (res.status === 401) {
|
||||
clearAuth();
|
||||
}
|
||||
|
||||
const data = (await res.json().catch(() => ({}))) as any;
|
||||
|
||||
if (!res.ok) {
|
||||
throw new ApiError(data?.message || `请求失败: ${res.status}`, res.status);
|
||||
}
|
||||
|
||||
return data as T;
|
||||
}
|
||||
|
||||
export const api = {
|
||||
adminLogin: (identifier: string, password: string) =>
|
||||
request<any>('/admin/auth/login', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ identifier, password }),
|
||||
}),
|
||||
|
||||
listUsers: (limit = 100, offset = 0) =>
|
||||
request<any>(`/admin/users?limit=${encodeURIComponent(limit)}&offset=${encodeURIComponent(offset)}`),
|
||||
|
||||
resetUserPassword: (userId: string, newPassword: string) =>
|
||||
request<any>(`/admin/users/${encodeURIComponent(userId)}/reset-password`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ new_password: newPassword }),
|
||||
}),
|
||||
};
|
||||
Reference in New Issue
Block a user