Files
Toolbox/apps/app_order_box/kits/motion_reminder/api.ts
T

97 lines
2.9 KiB
TypeScript

import axios from 'axios';
import { ApiEnvelope, MotionCard, MotionSession } from './types';
const API_BASE_URL = 'http://47.101.56.101:8976/api/app_order_box';
const MOTION_BASE = `${API_BASE_URL}/kits/motion_reminder`;
const api = axios.create({
baseURL: API_BASE_URL,
timeout: 15000,
headers: {
'Content-Type': 'application/json',
},
});
const formatError = (error: any): string => {
if (error?.response) {
return `服务器响应 ${error.response.status}: ${error.response.statusText}\n${JSON.stringify(error.response.data)}`;
}
if (error?.request) {
return `服务器无响应: 无法连接到 ${API_BASE_URL}`;
}
if (error?.message) {
return `请求错误: ${error.message}`;
}
return '未知错误';
};
export const motionReminderApi = {
async listCards(): Promise<MotionCard[]> {
try {
const response = await api.get<ApiEnvelope<MotionCard[]>>(`${MOTION_BASE}/cards`);
return response.data.data || [];
} catch (error) {
throw new Error(formatError(error));
}
},
async saveCard(card: Partial<MotionCard>): Promise<MotionCard> {
try {
const response = card.id
? await api.put<ApiEnvelope<MotionCard>>(`${MOTION_BASE}/cards`, card)
: await api.post<ApiEnvelope<MotionCard>>(`${MOTION_BASE}/cards`, card);
if (!response.data.ok || !response.data.data) {
throw new Error(response.data.error || '保存失败');
}
return response.data.data;
} catch (error) {
throw new Error(formatError(error));
}
},
async deleteCard(id: string): Promise<void> {
try {
await api.delete(`${MOTION_BASE}/cards`, { params: { id } });
} catch (error) {
throw new Error(formatError(error));
}
},
async listHistory(): Promise<MotionSession[]> {
try {
const response = await api.get<ApiEnvelope<MotionSession[]>>(`${MOTION_BASE}/history`);
return response.data.data || [];
} catch (error) {
throw new Error(formatError(error));
}
},
async startSession(card: MotionCard): Promise<MotionSession> {
try {
const response = await api.post<ApiEnvelope<MotionSession>>(`${MOTION_BASE}/sessions/start`, { card });
if (!response.data.ok || !response.data.data) {
throw new Error(response.data.error || '启动失败');
}
return response.data.data;
} catch (error) {
throw new Error(formatError(error));
}
},
async syncSession(payload: Partial<MotionSession> & { id: string }): Promise<void> {
try {
await api.post(`${MOTION_BASE}/sessions/sync`, payload);
} catch (error) {
throw new Error(formatError(error));
}
},
async finishSession(payload: Partial<MotionSession> & { id: string; status: 'completed' | 'stopped' }): Promise<void> {
try {
await api.post(`${MOTION_BASE}/sessions/finish`, payload);
} catch (error) {
throw new Error(formatError(error));
}
},
};