/** * 广播消息本地模拟后端(一期用,NOTICE_MOCK = true 生效) * * 用 storage 模拟「服务端消息表 + 长轮询」: * - mockSend 写入一条消息 * - mockPoll 在 since_id 之后找新消息,没有就每 200ms 轮询一次, * 直到有新消息(模拟服务端 hold 立即返回)或到达挂起上限 * * 限制:一台设备一份 storage,所以只能在同一浏览器(多标签页共享) * 或同一台设备内验证;真实跨设备收发需后端就绪。 */ import { NOTICE_STORAGE } from '@/config/notice' const MAX_ROWS = 100 function readDb() { try { const rows = uni.getStorageSync(NOTICE_STORAGE.mockDb) return Array.isArray(rows) ? rows : [] } catch (e) { return [] } } function writeDb(rows) { try { uni.setStorageSync(NOTICE_STORAGE.mockDb, rows) } catch (e) { // storage 写入失败不阻断交互 } } function formatTime(date) { const pad = (n) => (n < 10 ? `0${n}` : String(n)) return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad( date.getHours() )}:${pad(date.getMinutes())}:${pad(date.getSeconds())}` } function nextId(rows) { const maxId = rows.reduce((max, row) => Math.max(max, Number(row.id) || 0), 0) // 用时间戳做 id,保证与 since_id 单调递增 return Math.max(Date.now(), maxId + 1) } /** 模拟服务端「发送广播」 */ export function mockSend(payload = {}) { const rows = readDb() const msg = { id: nextId(rows), content: payload.content || '', audio_url: payload.audio_url || '', duration: Number(payload.duration || 0), priority: Number(payload.priority || 0) === 1 ? 1 : 0, target_type: payload.target_type || 'all', target_ids: payload.target_ids || [], sender_name: payload.sender_name || '本机', sender_workbench_id: payload.sender_workbench_id || '', created_at: formatTime(new Date()), expire_at: '', } rows.unshift(msg) writeDb(rows.slice(0, MAX_ROWS)) console.log('[notice-mock] 已写入消息:', JSON.stringify(msg)) return msg } /** * 模拟服务端「长轮询」 * - 有新消息:立即返回(模拟服务端 hold 到新消息即回) * - 无新消息:每 200ms 检查一次,直到达到挂起上限(mock 上限 5s,避免调试等太久) */ export function mockPoll(sinceId = 0, timeout = 0) { const deadline = Date.now() + Math.min(Number(timeout) || 0, 5000) const from = Number(sinceId) || 0 return new Promise((resolve) => { const tick = () => { const rows = readDb() const list = rows .filter((row) => Number(row.id) > from) .sort((a, b) => Number(a.id) - Number(b.id)) if (list.length) { resolve({ list, last_id: list[list.length - 1].id }) return } if (Date.now() >= deadline) { resolve({ list: [], last_id: from }) return } setTimeout(tick, 200) } tick() }) } /** 当前模拟消息表里最大的消息 id(mock 启动时用它跳过历史,避免刷新后重播旧消息) */ export function mockLatestId() { const rows = readDb() return rows.reduce((max, row) => Math.max(max, Number(row.id) || 0), 0) } /** 清空模拟消息表 */ export function mockReset() { try { uni.removeStorageSync(NOTICE_STORAGE.mockDb) } catch (e) { // 忽略 } }