SolyQuiz/lib/notifications.ts
corenthin-lebreton c499c452f0 new modif
2026-02-27 00:10:09 +01:00

45 lines
1.4 KiB
TypeScript

import { createAdminClient } from '@/lib/supabase/server'
export type NotificationType =
| 'session_created'
| 'student_joined'
| 'session_ended'
const typeConfig: Record<NotificationType, { icon: string; defaultTitle: string }> = {
session_created: { icon: '🚀', defaultTitle: 'Session créée' },
student_joined: { icon: '👤', defaultTitle: 'Étudiant rejoint' },
session_ended: { icon: '✅', defaultTitle: 'Session terminée' },
}
interface CreateNotificationOptions {
userId: string
type: NotificationType
title?: string
body: string
metadata?: Record<string, unknown>
}
/**
* Insère une notification en base pour un utilisateur.
* Utilise le client admin (service_role) pour bypasser RLS sur l'INSERT.
* Les erreurs sont loggées mais n'interrompent pas le flux appelant.
*/
export async function createNotification(opts: CreateNotificationOptions): Promise<void> {
try {
const admin = createAdminClient() as any
const cfg = typeConfig[opts.type]
const { error } = await admin.from('notifications').insert({
user_id: opts.userId,
type: opts.type,
title: opts.title ?? cfg.defaultTitle,
body: opts.body,
metadata: opts.metadata ?? {},
})
if (error) console.error('[createNotification]', error.message)
} catch (err) {
console.error('[createNotification] unexpected error', err)
}
}