import { Injectable, Logger } from '@nestjs/common'; import { NotificationGateway, WS_NOTIFICATION_EVENT, } from './notification.gateway'; /** * WebSocket 通知事件发射器 * @description 封装 NotificationGateway 的推送能力,提供面向业务层的事件发射接口。 * 可被 Core 层的事件监听器注入使用,实现领域事件到 WebSocket 的桥接。 */ @Injectable() export class WsNotificationEmitter { private readonly logger = new Logger(WsNotificationEmitter.name); constructor(private readonly gateway: NotificationGateway) {} /** * 向指定用户推送 WebSocket 事件 * @param userId - 目标用户 ID * @param event - 事件名称(默认使用 'notification') * @param data - 事件负载数据 */ async emitToUser( userId: string, event: string = WS_NOTIFICATION_EVENT, data: unknown, ): Promise { if (!userId || typeof userId !== 'string') { this.logger.warn('emitToUser called with invalid userId, skipping'); return; } try { await this.gateway.sendToUser(userId, { event, data }); } catch (error) { this.logger.error( `Failed to emit WebSocket event to userId=${userId}: ${error instanceof Error ? error.message : String(error)}`, ); } } }