mockApi.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. const mockApi = {
  2. members: [
  3. { _id: '1', name: '张三', attendance: [] },
  4. { _id: '2', name: '李四', attendance: [] },
  5. ],
  6. devices: [
  7. { _id: '1', name: '设备1', deviceId: 'DEV001', status: 'online' },
  8. { _id: '2', name: '设备2', deviceId: 'DEV002', status: 'offline' },
  9. ],
  10. };
  11. const mockApiHandlers = {
  12. '/api/members': async () => mockApi.members,
  13. '/api/devices': async () => mockApi.devices,
  14. '/api/members': async (method, body) => {
  15. if (method === 'POST') {
  16. const newMember = { _id: String(mockApi.members.length + 1), name: body.name, attendance: [] };
  17. mockApi.members.push(newMember);
  18. return newMember;
  19. }
  20. return mockApi.members;
  21. },
  22. '/api/attendance': async (method, body) => {
  23. if (method === 'POST') {
  24. const { memberId, date } = body;
  25. const member = mockApi.members.find(m => m._id === memberId);
  26. if (member) {
  27. member.attendance.push(date);
  28. return member;
  29. }
  30. throw new Error('会员不存在');
  31. }
  32. },
  33. };
  34. async function callMockApi(url, method = 'GET', body = null) {
  35. const handler = mockApiHandlers[url.split('?')[0]];
  36. if (handler) {
  37. return await handler(method, body);
  38. }
  39. throw new Error('Not found');
  40. }
  41. window.mockApi = {
  42. fetch: async (url, options = {}) => {
  43. try {
  44. const result = await callMockApi(url, options.method, options.body ? JSON.parse(options.body) : null);
  45. return {
  46. ok: true,
  47. json: async () => result,
  48. };
  49. } catch (error) {
  50. return {
  51. ok: false,
  52. status: 404,
  53. json: async () => ({ message: error.message }),
  54. };
  55. }
  56. }
  57. };