New abstract structure

Events for invoices get emitted in rooms
This commit is contained in:
2020-12-28 19:04:13 +01:00
parent 7f8ae69e2e
commit 0b3502d81f
14 changed files with 467 additions and 229 deletions

View File

@@ -6,16 +6,9 @@ import { PaymentStatus } from "./types";
export class SocketManager {
io: Server;
private socketInvoice: Map<string, string>; // Socket ID / _id
private idSocket: Map<string, Socket>; // Socket ID / Socket
private invoiceSocket: Map<string, Socket>; // _id / Socket
constructor(io: Server) {
this.io = io;
this.socketInvoice = new Map<string, string>();
this.idSocket = new Map<string, Socket>();
this.invoiceSocket = new Map<string, Socket>();
this.listen();
}
@@ -23,8 +16,6 @@ export class SocketManager {
console.log("Listen");
this.io.on('connection', (socket: Socket) => {
this.idSocket.set(socket.id, socket);
// The frontend sends his selector, then pick _id and put it in `socketInvoice` map.
// Return `true` if successful and `false` if not.
socket.on('subscribe', async data => {
@@ -36,25 +27,13 @@ export class SocketManager {
}
logger.info(`Socket ${socket.id} has subscribed to invoice ${invoice.id} (${PaymentStatus[invoice.status]})`);
this.socketInvoice.set(socket.id, invoice.id);
this.invoiceSocket.set(invoice.id, socket);
socket.emit('subscribe', true);
}
});
});
}
getSocketById(id: string) {
return this.idSocket.get(id);
}
async getInvoiceBySocket(socketId: string) {
const invoiceId = this.socketInvoice.get(socketId);
return await Invoice.findById(invoiceId);
}
getSocketByInvoice(invoice: IInvoice) {
return this.invoiceSocket.get(invoice.id);
emitInvoiceEvent(invoice: IInvoice, event: string, data: any) {
logger.debug(`Broadcast ${data} to room ${invoice.selector}`);
this.io.to(invoice.selector).emit(event, data);
}
}