diff --git a/libs/common/src/helper/services/device.messages.service.ts b/libs/common/src/helper/services/device.messages.service.ts new file mode 100644 index 0000000..c51f6f4 --- /dev/null +++ b/libs/common/src/helper/services/device.messages.service.ts @@ -0,0 +1,53 @@ +import { Injectable } from '@nestjs/common'; +import { DeviceNotificationRepository } from '@app/common/modules/device-notification/repositories'; +import { OneSignalService } from './onesignal.service'; + +@Injectable() +export class DeviceMessagesService { + constructor( + private readonly deviceNotificationRepository: DeviceNotificationRepository, + private readonly oneSignalService: OneSignalService, + ) {} + + async getDevicesUserNotifications(deviceTuyaUuid: string, bizData: any) { + try { + // Retrieve notifications for the specified device + const notifications = await this.deviceNotificationRepository.find({ + where: { + device: { + deviceTuyaUuid, + }, + }, + relations: ['user', 'user.userNotification'], + }); + + // If notifications are found, send them + if (notifications) { + await this.sendNotifications(notifications, bizData); + } + } catch (error) { + console.error('Error fetching device notifications:', error); + } + } + + private async sendNotifications(notifications: any[], bizData: any) { + const notificationPromises = []; + + // Iterate over each notification and its associated user notifications + notifications.forEach((notification) => { + notification.user.userNotification.forEach((userNotification) => { + // Queue notification sending without awaiting + notificationPromises.push( + this.oneSignalService.sendNotification( + JSON.stringify(bizData), + 'device-status', + [userNotification.subscriptionUuid], + ), + ); + }); + }); + + // Wait for all notification sending operations to complete + await Promise.all(notificationPromises); + } +}