Include app source and update .gitignore to exclude local release artifacts and signing files. Made-with: Cursor
53 lines
1.3 KiB
TypeScript
53 lines
1.3 KiB
TypeScript
export type CacheEventType =
|
|
| 'list_updated'
|
|
| 'detail_updated'
|
|
| 'cache_state_updated'
|
|
| 'error';
|
|
|
|
export interface CacheEvent<TPayload = any> {
|
|
type: CacheEventType;
|
|
payload: TPayload;
|
|
timestamp: number;
|
|
}
|
|
|
|
export type CacheSubscriber<TEvent extends CacheEvent = CacheEvent> = (event: TEvent) => void;
|
|
|
|
/**
|
|
* 统一缓存总线基座:
|
|
* - 单一订阅入口
|
|
* - 统一事件通知
|
|
* - 新订阅立即收到快照
|
|
*/
|
|
export abstract class CacheBus<TSnapshot, TEvent extends CacheEvent = CacheEvent> {
|
|
private subscribers = new Set<CacheSubscriber<TEvent>>();
|
|
|
|
protected abstract getSnapshot(): TSnapshot;
|
|
|
|
protected notify(event: TEvent): void {
|
|
this.subscribers.forEach((subscriber) => {
|
|
try {
|
|
subscriber(event);
|
|
} catch (error) {
|
|
console.error('[CacheBus] subscriber error:', error);
|
|
}
|
|
});
|
|
}
|
|
|
|
subscribe(subscriber: CacheSubscriber<TEvent>): () => void {
|
|
this.subscribers.add(subscriber);
|
|
this.emitInitialSnapshot(subscriber);
|
|
return () => {
|
|
this.subscribers.delete(subscriber);
|
|
};
|
|
}
|
|
|
|
protected emitInitialSnapshot(subscriber: CacheSubscriber<TEvent>): void {
|
|
subscriber({
|
|
type: 'cache_state_updated',
|
|
payload: this.getSnapshot(),
|
|
timestamp: Date.now(),
|
|
} as TEvent);
|
|
}
|
|
}
|
|
|