From c6472013a368e1845458190f01cf21b8ab7d8bd5 Mon Sep 17 00:00:00 2001 From: Sergey Yarkov Date: Mon, 28 Feb 2022 21:39:34 +0300 Subject: [PATCH] feat: delete notifications --- app/Services/WsService.ts | 23 ++++++++++++++++++++--- app/Store/NotificationStore.ts | 8 ++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/app/Services/WsService.ts b/app/Services/WsService.ts index 65fb100..5d6370d 100644 --- a/app/Services/WsService.ts +++ b/app/Services/WsService.ts @@ -31,7 +31,13 @@ export interface ServerToClientEvents { /** * Chat */ - 'chat:message': (data: { content: string; time: string; from: string; to: string; notificationId: string }) => void; + 'chat:message': (data: { + content: string; + time: string; + from: string; + to: string; + notificationId?: string | undefined; + }) => void; } export interface ClientToServerEvents { @@ -45,6 +51,11 @@ export interface ClientToServerEvents { * Chat */ 'chat:message': (data: { content: string; to: string }) => void; + + /** + * Notification + */ + 'notification:read': (data: { userId: string; ids: string[] }) => void; } export interface InterServerEvents {} @@ -130,11 +141,17 @@ class WsService { await this.messageStore.add(userId, to, message); - const notification = await this.notificationStore.add(to, `You received a new private message`, 'MESSAGE'); - this.io.to(to).emit('chat:message', { ...message, notificationId: notification.id }); + if (userId !== to) { + const notification = await this.notificationStore.add(to, `You received a new private message`, 'MESSAGE'); + this.io.to(to).emit('chat:message', { ...message, notificationId: notification.id }); + } else { + this.io.to(to).emit('chat:message', { ...message }); + } } }); + socket.on('notification:read', data => this.notificationStore.del(data.userId, data.ids)); + /** * Destroy session on user logout request */ diff --git a/app/Store/NotificationStore.ts b/app/Store/NotificationStore.ts index bd42094..50e90e0 100644 --- a/app/Store/NotificationStore.ts +++ b/app/Store/NotificationStore.ts @@ -50,6 +50,14 @@ class RedisNotificationStore { const notification = (await this.redisClient.hgetall(key)) as NotificationType; return notification; } + + public async del(userId: string, keys: string[]): Promise { + const k = keys.map(v => `notification:${v}`); + const count = await this.redisClient.zrem(`user:${userId}`, k); + await this.redisClient.del(k); + + return count; + } } export default RedisNotificationStore;