add device messages services to send notification

This commit is contained in:
faris Aljohari
2024-05-26 00:38:22 +03:00
parent bb9b043be9
commit cff8ac1c5c

View File

@ -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);
}
}