58 lines
1.8 KiB
TypeScript
58 lines
1.8 KiB
TypeScript
// user.listener.ts
|
|
import { Message } from '@/entities/message.entity';
|
|
import { Injectable } from '@nestjs/common';
|
|
import { EventEmitter2 } from '@nestjs/event-emitter';
|
|
import { InjectRepository } from '@nestjs/typeorm';
|
|
import { Repository } from 'typeorm';
|
|
|
|
@Injectable()
|
|
export class MessagesEventService {
|
|
public static EVENTS = {
|
|
GET_CONVERSATIONS: 'messages.get-conversations',
|
|
GET_CONVERSATION: 'messages.get-conversation',
|
|
RECEIVE_CONVERSATIONS: 'messages.receive-conversations',
|
|
RECEIVE_CONVERSATION: 'messages.receive-conversation',
|
|
SEND_MESSAGE: 'messages.send-messsage',
|
|
REPLY_MESSAGE: 'messages.reply-messsage',
|
|
};
|
|
|
|
public static LOCAL_EVENTS = {
|
|
GET_CONVERSATIONS: 'local_messages.get-conversations',
|
|
GET_CONVERSATION: 'local_messages.get-conversation',
|
|
RECEIVE_CONVERSATIONS: 'local_messages.receive-conversations',
|
|
RECEIVE_CONVERSATION: 'local_messages.receive-conversation',
|
|
SEND_MESSAGE: 'local_messages.send-messsage',
|
|
REPLY_MESSAGE: 'local_messages.reply-messsage',
|
|
};
|
|
|
|
constructor(
|
|
private event: EventEmitter2,
|
|
@InjectRepository(Message)
|
|
readonly repo: Repository<Message>,
|
|
) {}
|
|
|
|
public async waitForEvent<T>(
|
|
eventName: string,
|
|
timeoutMs = 10000,
|
|
): Promise<T> {
|
|
return new Promise((resolve, reject) => {
|
|
const timer = setTimeout(() => {
|
|
this.event.off(eventName, listener); // cleanup
|
|
resolve(null); // hoặc reject(new Error('Timeout')) nếu muốn
|
|
}, timeoutMs);
|
|
|
|
const listener = (data: any) => {
|
|
clearTimeout(timer);
|
|
this.event.off(eventName, listener); // cleanup
|
|
resolve(data);
|
|
};
|
|
|
|
this.event.on(eventName, listener);
|
|
});
|
|
}
|
|
|
|
public async sendEvent<T>(eventName: string, data: T) {
|
|
return this.event.emit(eventName, data);
|
|
}
|
|
}
|