t-comm
Version:
专业、稳定、纯粹的工具库
103 lines (102 loc) • 3.53 kB
TypeScript
/**
* BumpService —— 碰一碰业务编排层
*
* 职责:
* 1. 状态机管理(Idle → Starting → Scanning → Reporting → Matched/Failed)
* 2. 调用后端 4 个接口(通过注入的 BumpApiAdapter)
* 3. tempId 自动刷新(3 分钟过期窗口内提前刷新)
* 4. 附近设备缓存(NearbyPeer Map + 持久化)
* 5. 事件派发(通过注入的 BumpEventBus)
*
* 设计原则:
* - 不依赖任何框架(无 oops / cc / vue / react)
* - 不依赖具体 HTTP 库(通过 BumpApiAdapter 注入)
* - 不依赖蓝牙实现(与 bluetooth-bump 解耦,通过回调协作)
* - 纯 TypeScript,可在任何小程序/Web 环境运行
*
* 使用方式:
* const service = new BumpService({
* api: myApiAdapter,
* eventBus: myEventBus,
* storage: myStorage,
* });
* await service.start({ actId: 'xxx' });
* // 蓝牙层 onBump 回调时:
* const result = await service.bumpPeer(peerTempId, rssi);
*/
import { BumpPhase, type BumpServiceOptions, type BumpStartOptions, type BumpPeerResult, type NearbyPeer, type GetPeerByTempIdRsp } from './types';
export declare class BumpService {
/** 当前阶段 */
phase: BumpPhase;
/** 我方 tempId(BumpStart 后获得) */
myTempId: string;
/** tempId 过期时间戳 */
expireAt: number;
/** 活动 ID */
actId: string;
/** 当前匹配 ID(Report 成功后获得) */
matchId: string;
/** 当前正在碰的 peerTempId */
currentPeerTempId: string;
/** 附近设备缓存 */
nearbyPeers: Map<string, NearbyPeer>;
private readonly api;
private readonly eventBus;
private readonly storage;
private readonly logger;
private readonly tempIdRefreshMs;
private readonly peerCacheTtlMs;
private refreshTimer;
private pruneTimer;
/** 正在进行中的 bumpPeer 调用(防重复点击) */
private bumpingSet;
constructor(options: BumpServiceOptions);
/**
* 启动碰一碰会话
* 1. 调用 BumpStart 拿 tempId
* 2. 启动 tempId 自动刷新定时器
* 3. 加载持久化缓存
*
* 返回 tempId 供蓝牙层使用
*/
start(options?: BumpStartOptions): Promise<string>;
/**
* 停止碰一碰会话
*/
stop(): void;
/**
* 碰一碰核心流程:上报 + 领奖
* @param peerTempId 对端的 tempId
* @param rssi 信号强度(可选)
*/
bumpPeer(peerTempId: string, rssi?: number): Promise<BumpPeerResult>;
/**
* 注册附近设备(蓝牙层 onDeviceFound 时调用)
* @param peerTempId 对端 tempId(从 BLE payload 解析)
* @param deviceId BLE 设备 ID
* @param rssi 信号强度
*/
registerNearbyPeer(peerTempId: string, deviceId: string, rssi: number): void;
/**
* 获取对端用户信息(用于 UI 展示昵称/头像)
*/
fetchPeerInfo(peerTempId: string): Promise<GetPeerByTempIdRsp | null>;
/**
* 获取附近设备缓存快照(只返回 TTL 内的)
*/
getNearbyPeerCache(): NearbyPeer[];
/**
* 手动刷新 tempId(也可由定时器自动触发)
*/
refreshTempId(): Promise<string>;
private setPhase;
private fail;
private softFail;
private startRefreshTimer;
private clearRefreshTimer;
private startPruneTimer;
private clearPruneTimer;
private pruneExpiredPeers;
private saveNearbyPeerCache;
private loadNearbyPeerCache;
}