// API 调用封装 const API_BASE = '/api'; async function apiRequest(url, options = {}) { const res = await fetch(url, { ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); if (!res.ok) { let errorMsg = `请求失败 (${res.status})`; try { const data = await res.json(); if (data.error) errorMsg = data.error; else if (data.detail) errorMsg = data.detail; } catch { // response not JSON } throw new Error(errorMsg); } // 204 No Content if (res.status === 204) return null; return res.json(); } const API = { // 菜品相关 async getDishes(params = {}) { const query = new URLSearchParams(params).toString(); return apiRequest(`${API_BASE}/dishes/${query ? '?' + query : ''}`); }, async getDish(id) { return apiRequest(`${API_BASE}/dishes/${id}/`); }, async createDish(data) { return apiRequest(`${API_BASE}/dishes/`, { method: 'POST', body: JSON.stringify(data), }); }, async updateDish(id, data) { return apiRequest(`${API_BASE}/dishes/${id}/`, { method: 'PATCH', body: JSON.stringify(data), }); }, async deleteDish(id) { return apiRequest(`${API_BASE}/dishes/${id}/`, { method: 'DELETE' }); }, // 分类相关 async getCategories() { return apiRequest(`${API_BASE}/categories/`); }, // 订单相关 async getOrders(params = {}) { const query = new URLSearchParams(params).toString(); return apiRequest(`${API_BASE}/orders/${query ? '?' + query : ''}`); }, async createOrder(data) { return apiRequest(`${API_BASE}/orders/`, { method: 'POST', body: JSON.stringify(data), }); }, async completeOrder(id) { return apiRequest(`${API_BASE}/orders/${id}/complete/`, { method: 'POST' }); }, async deleteOrder(id) { return apiRequest(`${API_BASE}/orders/${id}/`, { method: 'DELETE' }); }, // URL解析 async parseUrl(url) { return apiRequest(`${API_BASE}/parse-url/`, { method: 'POST', body: JSON.stringify({ url }), }); }, // 图片上传 async uploadImage(file) { const formData = new FormData(); formData.append('image', file); const res = await fetch('/upload-image/', { method: 'POST', body: formData, }); if (!res.ok) { let errorMsg = `上传失败 (${res.status})`; try { const data = await res.json(); if (data.error) errorMsg = data.error; } catch { // response not JSON } throw new Error(errorMsg); } return res.json(); }, };