Procházet zdrojové kódy

AI: 实现模拟API和API切换功能

D8D AI před 1 rokem
rodič
revize
d64a61d8a3
2 změnil soubory, kde provedl 85 přidání a 5 odebrání
  1. 25 5
      public/index.html
  2. 60 0
      public/mockApi.js

+ 25 - 5
public/index.html

@@ -14,6 +14,11 @@
     <div class="container">
         <h1 class="mb-4">会友信息考勤打卡系统</h1>
         
+        <div class="form-check form-switch mb-3">
+            <input class="form-check-input" type="checkbox" id="apiToggle">
+            <label class="form-check-label" for="apiToggle">使用模拟API</label>
+        </div>
+
         <form id="addMemberForm" class="mb-4">
             <div class="input-group">
                 <input type="text" id="memberName" class="form-control" placeholder="输入会员姓名" required>
@@ -29,11 +34,26 @@
     </div>
 
     <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
+    <script src="/mockApi.js"></script>
     <script>
         const API_URL = '/api';
+        let useMockApi = false;
+
+        document.getElementById('apiToggle').addEventListener('change', (e) => {
+            useMockApi = e.target.checked;
+            fetchMembers();
+            fetchDevices();
+        });
+
+        async function apiFetch(url, options = {}) {
+            if (useMockApi) {
+                return window.mockApi.fetch(url, options);
+            }
+            return fetch(url, options);
+        }
 
         async function fetchMembers() {
-            const response = await fetch(`${API_URL}/members`);
+            const response = await apiFetch(`${API_URL}/members`);
             const members = await response.json();
             const memberList = document.getElementById('memberList');
             memberList.innerHTML = members.map(member => `
@@ -50,7 +70,7 @@
         document.getElementById('addMemberForm').addEventListener('submit', async (e) => {
             e.preventDefault();
             const name = document.getElementById('memberName').value;
-            await fetch(`${API_URL}/members`, {
+            await apiFetch(`${API_URL}/members`, {
                 method: 'POST',
                 headers: { 'Content-Type': 'application/json' },
                 body: JSON.stringify({ name })
@@ -61,7 +81,7 @@
 
         async function recordAttendance(memberId) {
             const date = new Date().toISOString().split('T')[0];
-            await fetch(`${API_URL}/attendance`, {
+            await apiFetch(`${API_URL}/attendance`, {
                 method: 'POST',
                 headers: { 'Content-Type': 'application/json' },
                 body: JSON.stringify({ memberId, date })
@@ -70,13 +90,13 @@
         }
 
         async function viewAttendance(memberId) {
-            const response = await fetch(`${API_URL}/attendance/${memberId}`);
+            const response = await apiFetch(`${API_URL}/attendance/${memberId}`);
             const attendance = await response.json();
             alert(`考勤记录:\n${attendance.join('\n')}`);
         }
 
         async function fetchDevices() {
-            const response = await fetch(`${API_URL}/devices`);
+            const response = await apiFetch(`${API_URL}/devices`);
             const devices = await response.json();
             const deviceList = document.getElementById('deviceList');
             deviceList.innerHTML = devices.map(device => `

+ 60 - 0
public/mockApi.js

@@ -0,0 +1,60 @@
+const mockApi = {
+  members: [
+    { _id: '1', name: '张三', attendance: [] },
+    { _id: '2', name: '李四', attendance: [] },
+  ],
+  devices: [
+    { _id: '1', name: '设备1', deviceId: 'DEV001', status: 'online' },
+    { _id: '2', name: '设备2', deviceId: 'DEV002', status: 'offline' },
+  ],
+};
+
+const mockApiHandlers = {
+  '/api/members': async () => mockApi.members,
+  '/api/devices': async () => mockApi.devices,
+  '/api/members': async (method, body) => {
+    if (method === 'POST') {
+      const newMember = { _id: String(mockApi.members.length + 1), name: body.name, attendance: [] };
+      mockApi.members.push(newMember);
+      return newMember;
+    }
+    return mockApi.members;
+  },
+  '/api/attendance': async (method, body) => {
+    if (method === 'POST') {
+      const { memberId, date } = body;
+      const member = mockApi.members.find(m => m._id === memberId);
+      if (member) {
+        member.attendance.push(date);
+        return member;
+      }
+      throw new Error('会员不存在');
+    }
+  },
+};
+
+async function callMockApi(url, method = 'GET', body = null) {
+  const handler = mockApiHandlers[url.split('?')[0]];
+  if (handler) {
+    return await handler(method, body);
+  }
+  throw new Error('Not found');
+}
+
+window.mockApi = {
+  fetch: async (url, options = {}) => {
+    try {
+      const result = await callMockApi(url, options.method, options.body ? JSON.parse(options.body) : null);
+      return {
+        ok: true,
+        json: async () => result,
+      };
+    } catch (error) {
+      return {
+        ok: false,
+        status: 404,
+        json: async () => ({ message: error.message }),
+      };
+    }
+  }
+};