feat: count failed attempts

This commit is contained in:
Nathan Lamy 2025-08-21 11:39:14 +02:00
parent 169df9715e
commit 6213f3941c

View file

@ -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) {
try {
await this.pushNotification(subscription.data, payload)
// TODO: Count failed attempts and disable subscription if too many failures
// 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()
}
}
}