From 6213f3941c75d900147bbdc11f5a4ca5dff1be58 Mon Sep 17 00:00:00 2001 From: Nathan Lamy Date: Thu, 21 Aug 2025 11:39:14 +0200 Subject: [PATCH] feat: count failed attempts --- app/services/notification_service.ts | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/app/services/notification_service.ts b/app/services/notification_service.ts index 6b7343a..04f03f9 100644 --- a/app/services/notification_service.ts +++ b/app/services/notification_service.ts @@ -5,6 +5,8 @@ import { DateTime } from 'luxon' import { UAParser } from 'ua-parser-js' import webpush, { PushSubscription } from 'web-push' +const MAX_FAILED_ATTEMPTS = 5 + export const EVENTS = { SYSTEM: 1 << 0, @@ -55,12 +57,28 @@ export class NotificationService { const subscriptions = await Subscription.query() .where('enabled', true) .where('userId', colle.studentId) - // TODO: Check if working?? .whereRaw(`(events & ${EVENTS[notificationId]}) > 0`) for (const subscription of subscriptions) { - await this.pushNotification(subscription.data, payload) - // TODO: Count failed attempts and disable subscription if too many failures + try { + await this.pushNotification(subscription.data, payload) + // Reset failed attempts on successful notification + if (subscription.failedAttempts) { + subscription.failedAttempts = 0 + await subscription.save() + } + } catch (err) { + console.error( + `Error sending notification for ${notificationId} to user ${colle.studentId}:`, + err + ) + // Increment failed attempts and disable subscription if too many failures + subscription.failedAttempts = (subscription.failedAttempts || 0) + 1 + if (subscription.failedAttempts >= MAX_FAILED_ATTEMPTS) { + subscription.enabled = false + } + await subscription.save() + } } }