Files
zhangmenu/static/js/api.js
T

115 lines
2.9 KiB
JavaScript
Raw Normal View History

2026-03-12 11:27:23 +08:00
// 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();
}
2026-03-12 11:27:23 +08:00
const API = {
// 菜品相关
async getDishes(params = {}) {
const query = new URLSearchParams(params).toString();
return apiRequest(`${API_BASE}/dishes/${query ? '?' + query : ''}`);
2026-03-12 11:27:23 +08:00
},
async getDish(id) {
return apiRequest(`${API_BASE}/dishes/${id}/`);
2026-03-12 11:27:23 +08:00
},
async createDish(data) {
return apiRequest(`${API_BASE}/dishes/`, {
2026-03-12 11:27:23 +08:00
method: 'POST',
body: JSON.stringify(data),
2026-03-12 11:27:23 +08:00
});
},
async updateDish(id, data) {
return apiRequest(`${API_BASE}/dishes/${id}/`, {
2026-03-12 11:27:23 +08:00
method: 'PATCH',
body: JSON.stringify(data),
2026-03-12 11:27:23 +08:00
});
},
async deleteDish(id) {
return apiRequest(`${API_BASE}/dishes/${id}/`, { method: 'DELETE' });
2026-03-12 11:27:23 +08:00
},
// 分类相关
async getCategories() {
return apiRequest(`${API_BASE}/categories/`);
2026-03-12 11:27:23 +08:00
},
// 订单相关
async getOrders(params = {}) {
const query = new URLSearchParams(params).toString();
return apiRequest(`${API_BASE}/orders/${query ? '?' + query : ''}`);
2026-03-12 11:27:23 +08:00
},
async createOrder(data) {
return apiRequest(`${API_BASE}/orders/`, {
2026-03-12 11:27:23 +08:00
method: 'POST',
body: JSON.stringify(data),
2026-03-12 11:27:23 +08:00
});
},
async completeOrder(id) {
return apiRequest(`${API_BASE}/orders/${id}/complete/`, { method: 'POST' });
2026-03-12 11:27:23 +08:00
},
async deleteOrder(id) {
return apiRequest(`${API_BASE}/orders/${id}/`, { method: 'DELETE' });
2026-03-12 11:27:23 +08:00
},
// URL解析
async parseUrl(url) {
return apiRequest(`${API_BASE}/parse-url/`, {
2026-03-12 11:27:23 +08:00
method: 'POST',
body: JSON.stringify({ url }),
2026-03-12 11:27:23 +08:00
});
},
// 图片上传
async uploadImage(file) {
const formData = new FormData();
formData.append('image', file);
const res = await fetch('/upload-image/', {
method: 'POST',
body: formData,
2026-03-12 11:27:23 +08:00
});
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);
}
2026-03-12 11:27:23 +08:00
return res.json();
},
2026-03-12 11:27:23 +08:00
};