diff --git a/src/services/booksApi.ts b/src/services/booksApi.ts index 046aaa5..51438d1 100644 --- a/src/services/booksApi.ts +++ b/src/services/booksApi.ts @@ -1,4 +1,5 @@ import type { TeachingBook } from '../domain/teachingDesign' +import { authedFetch } from '../composables/useAuth' export interface BookSummary { id: string @@ -25,52 +26,34 @@ export interface GenerateResult { markdown: string } -interface ErrorBody { - error?: string -} - -async function request(path: string, init?: RequestInit): Promise { - const response = await fetch(path, { - ...init, - headers: { 'Content-Type': 'application/json', ...(init?.headers ?? {}) }, - }) - - if (!response.ok) { - const body = (await response.json().catch(() => null)) as ErrorBody | null - throw new Error(body?.error ?? `请求失败(${response.status})。`) - } - - return response.json() as Promise -} - export function listBooks(): Promise { - return request('/api/books') + return authedFetch('/api/books') } export function createBook(name: string): Promise { - return request('/api/books', { method: 'POST', body: JSON.stringify({ name }) }) + return authedFetch('/api/books', { method: 'POST', body: JSON.stringify({ name }) }) } export function getBook(id: string): Promise { - return request(`/api/books/${id}`) + return authedFetch(`/api/books/${id}`) } export function updateBook(id: string, data: TeachingBook): Promise { - return request(`/api/books/${id}`, { method: 'PUT', body: JSON.stringify({ data }) }) + return authedFetch(`/api/books/${id}`, { method: 'PUT', body: JSON.stringify({ data }) }) } export function renameBook(id: string, name: string): Promise { - return request(`/api/books/${id}`, { method: 'PATCH', body: JSON.stringify({ name }) }) + return authedFetch(`/api/books/${id}`, { method: 'PATCH', body: JSON.stringify({ name }) }) } export function deleteBook(id: string): Promise<{ ok: true }> { - return request(`/api/books/${id}`, { method: 'DELETE' }) + return authedFetch(`/api/books/${id}`, { method: 'DELETE' }) } export function generateLesson(topic: string): Promise { - return request('/api/generate', { method: 'POST', body: JSON.stringify({ topic }) }) + return authedFetch('/api/generate', { method: 'POST', body: JSON.stringify({ topic }) }) } export function generateOutline(theme: string): Promise<{ titles: string[] }> { - return request('/api/generate/outline', { method: 'POST', body: JSON.stringify({ theme }) }) + return authedFetch('/api/generate/outline', { method: 'POST', body: JSON.stringify({ theme }) }) }