| 1 | /**
|
|---|
| 2 | * Notifications — reply to your comment, comment on your post, like on your post.
|
|---|
| 3 | * For every logged-in user (Google visitors/fans and admins). Snapshots of
|
|---|
| 4 | * actor name + post title so the list can be rendered without joins.
|
|---|
| 5 | */
|
|---|
| 6 | import { randomUUID } from 'crypto';
|
|---|
| 7 | import db from '../config/database.js';
|
|---|
| 8 |
|
|---|
| 9 | // Creates a notification. Does nothing if there is no recipient or if you
|
|---|
| 10 | // would notify yourself (your own comment/like on your own post/comment).
|
|---|
| 11 | export function notify({ userId, actorId, actorName, type, postSlug, postTitle, url }) {
|
|---|
| 12 | if (!userId || userId === actorId) return;
|
|---|
| 13 | try {
|
|---|
| 14 | db.prepare(`
|
|---|
| 15 | INSERT INTO user_notifications (id, user_id, type, actor_id, actor_name, post_slug, post_title, url, read)
|
|---|
| 16 | VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0)
|
|---|
| 17 | `).run(randomUUID(), userId, type, actorId || null, actorName || null, postSlug || null, postTitle || null, url || null);
|
|---|
| 18 | } catch { /* notifications are non-fatal */ }
|
|---|
| 19 | }
|
|---|
| 20 |
|
|---|
| 21 | export function unreadCount(userId) {
|
|---|
| 22 | if (!userId) return 0;
|
|---|
| 23 | try { return db.prepare('SELECT COUNT(*) AS c FROM user_notifications WHERE user_id = ? AND read = 0').get(userId).c; }
|
|---|
| 24 | catch { return 0; }
|
|---|
| 25 | }
|
|---|
| 26 |
|
|---|
| 27 | export function list(userId, limit = 50) {
|
|---|
| 28 | if (!userId) return [];
|
|---|
| 29 | try { return db.prepare('SELECT * FROM user_notifications WHERE user_id = ? ORDER BY created_at DESC LIMIT ?').all(userId, limit); }
|
|---|
| 30 | catch { return []; }
|
|---|
| 31 | }
|
|---|
| 32 |
|
|---|
| 33 | export function markAllRead(userId) {
|
|---|
| 34 | if (!userId) return;
|
|---|
| 35 | try { db.prepare('UPDATE user_notifications SET read = 1 WHERE user_id = ? AND read = 0').run(userId); } catch { /* no-op */ }
|
|---|
| 36 | }
|
|---|
| 37 |
|
|---|
| 38 | export default { notify, unreadCount, list, markAllRead };
|
|---|