// 后端接口基址:默认 /api/v1(开发时由 Vite 代理到 9999), // 也可以通过 VITE_API_BASE 环境变量覆盖为完整地址。 const API_BASE = import.meta.env.VITE_API_BASE || '/api/v1'; function authToken() { return localStorage.getItem('reader_token'); } async function request(path, options = {}) { const headers = { ...(options.headers || {}) }; const token = authToken(); if (token) headers.Authorization = `Bearer ${token}`; if (options.body !== undefined) headers['Content-Type'] = 'application/json'; const response = await fetch(`${API_BASE}${path}`, { method: options.method || 'GET', headers, body: options.body !== undefined ? JSON.stringify(options.body) : undefined, }); if (!response.ok) { let message = `请求失败(HTTP ${response.status})`; try { const data = await response.json(); if (data.message) message = data.message; if (data.detail) message = typeof data.detail === 'string' ? data.detail : JSON.stringify(data.detail); } catch { // 保留默认错误信息 } throw new Error(message); } return response.json(); } export const api = { home: () => request('/home'), categories: () => request('/categories'), category: (id, page = 1) => request(`/category/${encodeURIComponent(id)}?page=${page}`), search: (keyword) => request(`/search?keyword=${encodeURIComponent(keyword)}`), book: (bookId) => request(`/book/${encodeURIComponent(bookId)}`), bookTitle: (bookId) => request(`/book/${encodeURIComponent(bookId)}/title`), chapter: (bookId, chapterId) => request(`/chapter/${encodeURIComponent(bookId)}/${encodeURIComponent(chapterId)}`), chapterBatch: (bookId, chapterIds) => request(`/book/${encodeURIComponent(bookId)}/chapters/batch`, { method: 'POST', body: { chapter_ids: chapterIds }, }), // 用户 / 书架 / 进度 login: (username, password) => request('/auth/login', { method: 'POST', body: { username, password } }), me: () => request('/auth/me'), bookshelf: () => request('/bookshelf'), history: () => request('/history'), deleteHistory: (bookId) => request(`/history/${encodeURIComponent(bookId)}`, { method: 'DELETE' }), clearHistory: () => request('/history', { method: 'DELETE' }), addShelf: (bookId, title, author) => request('/bookshelf', { method: 'POST', body: { book_id: bookId, title, author } }), removeShelf: (bookId) => request(`/bookshelf/${encodeURIComponent(bookId)}`, { method: 'DELETE' }), progress: (bookId) => request(`/progress/${encodeURIComponent(bookId)}`), saveProgress: (bookId, chapterId, chapterTitle) => request('/progress', { method: 'POST', body: { book_id: bookId, chapter_id: chapterId, chapter_title: chapterTitle }, }), };