refactor: 抽离管理后台基础设施模块

This commit is contained in:
que01 committed 2026-09-19 18:44:47 +08:00
1 parent cfa183015b
commit d811478d0f
3 files changed
+26 -21

No files matched your search

+2 -5
View File
@@ -1,5 +1,5 @@
import { ApiClient } from "@personal-brand/api-client";
import { bootstrapAdmin } from "./main.js";
import { createApiClient } from "./lib/api.js";
const root = document.querySelector<HTMLElement>("#app");
if (root) {
@@ -11,10 +11,7 @@ if (root) {
const username = (root.querySelector("#username") as HTMLInputElement).value;
const password = (root.querySelector("#password") as HTMLInputElement).value;
try {
const client = new ApiClient({
baseUrl: import.meta.env.VITE_API_BASE_URL ?? "http://localhost:3001",
fetcher: (input, init) => fetch(input, init),
});
const client = createApiClient();
const result = await client.loginAdmin(username, password);
localStorage.setItem("adminToken", result.token);
location.reload();
+22
View File
@@ -0,0 +1,22 @@
import { ApiClient } from "@personal-brand/api-client";
export const apiBaseUrl = import.meta.env.VITE_API_BASE_URL ?? "http://localhost:3001";
export async function authenticatedFetch(
input: RequestInfo | URL,
init?: RequestInit,
): Promise<Response> {
const response = await fetch(input, init);
if (response.status === 401) {
localStorage.removeItem("adminToken");
window.dispatchEvent(new Event("admin-auth-expired"));
}
return response;
}
export function createApiClient(): ApiClient {
const token = localStorage.getItem("adminToken");
return new ApiClient({
baseUrl: apiBaseUrl,
...(token ? { token } : {}),
fetcher: authenticatedFetch,
});
}
+2 -16
View File
@@ -25,7 +25,7 @@ import {
Modal,
Badge,
} from "antd";
import { ApiClient } from "@personal-brand/api-client";
import { createApiClient } from "./lib/api.js";
import { BrowserRouter, Navigate, Route, Routes, useLocation, useNavigate } from "react-router-dom";
import type {
BrandProfile,
@@ -35,22 +35,8 @@ import type {
} from "@personal-brand/api-client";
import "antd/dist/reset.css";
const apiBaseUrl = import.meta.env.VITE_API_BASE_URL ?? "http://localhost:3001";
const queryClient = new QueryClient();
async function authenticatedFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
const response = await fetch(input, init);
if (response.status === 401) {
localStorage.removeItem("adminToken");
window.dispatchEvent(new Event("admin-auth-expired"));
}
return response;
}
const api = () =>
new ApiClient({
baseUrl: apiBaseUrl,
token: localStorage.getItem("adminToken") ?? undefined,
fetcher: authenticatedFetch,
});
const api = createApiClient;
function Login({ onLogin }: { onLogin: () => void }) {
const [form] = Form.useForm();