This commit is contained in:
pradeepkumar
2026-02-24 22:36:50 +05:30
parent 7ab5330a88
commit 36ccc8c303

View File

@@ -1,6 +1,7 @@
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { OnEvent } from '@nestjs/event-emitter';
import { Prisma } from '@prisma/client';
import * as admin from 'firebase-admin';
import { PrismaService } from '../prisma/prisma.service';
@@ -52,6 +53,11 @@ export class NotificationsService implements OnModuleInit {
this.logger.log('Firebase Admin initialized for push notifications');
}
private parseFcmTokens(raw: Prisma.JsonValue | null | undefined): FcmToken[] {
if (!raw || !Array.isArray(raw)) return [];
return raw as unknown as FcmToken[];
}
async registerToken(
userId: string,
token: string,
@@ -62,7 +68,7 @@ export class NotificationsService implements OnModuleInit {
select: { fcmTokens: true },
});
const existingTokens: FcmToken[] = (user?.fcmTokens as FcmToken[]) || [];
const existingTokens = this.parseFcmTokens(user?.fcmTokens);
// Remove existing entry for this token (if re-registering)
const filtered = existingTokens.filter((t) => t.token !== token);
@@ -75,7 +81,7 @@ export class NotificationsService implements OnModuleInit {
await this.prisma.user.update({
where: { id: userId },
data: { fcmTokens: filtered },
data: { fcmTokens: filtered as unknown as Prisma.InputJsonValue },
});
this.logger.log(`FCM token registered for user ${userId} (${device})`);
@@ -87,12 +93,17 @@ export class NotificationsService implements OnModuleInit {
select: { fcmTokens: true },
});
const existingTokens: FcmToken[] = (user?.fcmTokens as FcmToken[]) || [];
const existingTokens = this.parseFcmTokens(user?.fcmTokens);
const filtered = existingTokens.filter((t) => t.token !== token);
await this.prisma.user.update({
where: { id: userId },
data: { fcmTokens: filtered.length > 0 ? filtered : null },
data: {
fcmTokens:
filtered.length > 0
? (filtered as unknown as Prisma.InputJsonValue)
: Prisma.JsonNull,
},
});
this.logger.log(`FCM token removed for user ${userId}`);
@@ -125,7 +136,7 @@ export class NotificationsService implements OnModuleInit {
return;
}
const tokens: FcmToken[] = (user.fcmTokens as FcmToken[]) || [];
const tokens = this.parseFcmTokens(user.fcmTokens);
if (tokens.length === 0) {
this.logger.debug(`No FCM tokens for user ${userId}`);
return;
@@ -167,7 +178,10 @@ export class NotificationsService implements OnModuleInit {
await this.prisma.user.update({
where: { id: userId },
data: {
fcmTokens: validTokens.length > 0 ? validTokens : null,
fcmTokens:
validTokens.length > 0
? (validTokens as unknown as Prisma.InputJsonValue)
: Prisma.JsonNull,
},
});
this.logger.log(