From 61284731eec42ead211b5add5485172d381f26a2 Mon Sep 17 00:00:00 2001 From: Franck Royer Date: Fri, 22 Oct 2021 12:33:05 +1100 Subject: [PATCH] Instantiate all cahts with community --- packages/status-communities/src/messenger.ts | 49 ++++++++++++++++---- 1 file changed, 39 insertions(+), 10 deletions(-) diff --git a/packages/status-communities/src/messenger.ts b/packages/status-communities/src/messenger.ts index 69d175dc..618d8256 100644 --- a/packages/status-communities/src/messenger.ts +++ b/packages/status-communities/src/messenger.ts @@ -15,7 +15,11 @@ export class Messenger { chatsById: Map; observers: { [chatId: string]: Set< - (message: ApplicationMetadataMessage, timestamp: Date) => void + ( + message: ApplicationMetadataMessage, + timestamp: Date, + chatId: string + ) => void >; }; identity: Identity; @@ -49,6 +53,19 @@ export class Messenger { await this.joinChat(chat); } + /** + * Joins several of public chats. + * + * Use `addListener` to get messages received on these chats. + */ + public async joinChats(chats: Iterable): Promise { + await Promise.all( + Array.from(chats).map((chat) => { + return this.joinChat(chat); + }) + ); + } + /** * Joins a public chat. * @@ -110,18 +127,30 @@ export class Messenger { * @throws string If the chat has not been joined first using [joinChat]. */ public addObserver( - observer: (message: ApplicationMetadataMessage, timestamp: Date) => void, - chatId: string + observer: ( + message: ApplicationMetadataMessage, + timestamp: Date, + chatId: string + ) => void, + chatId: string | string[] ): void { - // Not sure this is the best design here. Maybe `addObserver` and `joinChat` should be merged. + let chats = []; - if (!this.chatsById.has(chatId)) - throw "Cannot add observer on a chat that is not joined."; - if (!this.observers[chatId]) { - this.observers[chatId] = new Set(); + if (typeof chatId === "string") { + chats.push(chatId); + } else { + chats = [...chatId]; } - this.observers[chatId].add(observer); + chats.forEach((id) => { + if (!this.chatsById.has(id)) + throw "Cannot add observer on a chat that is not joined."; + if (!this.observers[id]) { + this.observers[id] = new Set(); + } + + this.observers[id].add(observer); + }); } /** @@ -211,7 +240,7 @@ export class Messenger { if (this.observers[chat.id]) { this.observers[chat.id].forEach((observer) => { - observer(message, timestamp); + observer(message, timestamp, chat.id); }); } }