Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 | 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 48x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 4x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 4x 1x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 8x 8x 8x 8x 6x 2x 2x 8x 2x 8x 7x 2x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 6x 6x 2x 2x 2x 4x 2x 2x 2x 2x 4x 2x 3x 3x 2x 2x 2x 3x 2x 2x 2x 2x 2x 2x 2x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x | // src/services/db/notification.db.ts
import type { Pool, PoolClient } from 'pg';
import { getPool } from './connection.db';
import { NotFoundError, handleDbError } from './errors.db';
import type { Logger } from 'pino';
import type { Notification } from '../../types';
export class NotificationRepository {
// The repository only needs an object with a `query` method, matching the Pool/PoolClient interface.
// Using `Pick` makes this dependency explicit and simplifies testing by reducing the mock surface.
private db: Pick<Pool | PoolClient, 'query'>;
constructor(db: Pick<Pool | PoolClient, 'query'> = getPool()) {
this.db = db;
}
/**
* Inserts a single notification into the database.
* @param userId The ID of the user to notify.
* @param content The text content of the notification.
* @param linkUrl An optional URL for the notification to link to.
* @returns A promise that resolves to the newly created Notification object.
*/
async createNotification(
userId: string,
content: string,
logger: Logger,
linkUrl?: string,
): Promise<Notification> {
try {
const res = await this.db.query<Notification>(
`INSERT INTO public.notifications (user_id, content, link_url) VALUES ($1, $2, $3) RETURNING *`,
[userId, content, linkUrl || null],
);
return res.rows[0];
} catch (error) {
handleDbError(
error,
logger,
'Database error in createNotification',
{ userId, content, linkUrl },
{
fkMessage: 'The specified user does not exist.',
defaultMessage: 'Failed to create notification.',
},
);
}
}
/**
* Inserts multiple notifications into the database in a single query.
* This is more efficient than inserting one by one.
* @param notifications An array of notification objects to be inserted.
*/
async createBulkNotifications(
notifications: Omit<
Notification,
'notification_id' | 'is_read' | 'created_at' | 'updated_at'
>[],
logger: Logger,
): Promise<void> {
if (notifications.length === 0) {
return;
}
// This method assumes it might be part of a larger transaction, so it uses `this.db`.
// The calling service is responsible for acquiring and releasing a client if needed.
try {
// This is the secure way to perform bulk inserts.
// We use the `unnest` function in PostgreSQL to turn arrays of parameters
// into a set of rows that can be inserted. This avoids string concatenation
// and completely prevents SQL injection.
const query = `
INSERT INTO public.notifications (user_id, content, link_url)
SELECT * FROM unnest($1::uuid[], $2::text[], $3::text[])
`;
const userIds = notifications.map((n) => n.user_id);
const contents = notifications.map((n) => n.content);
const linkUrls = notifications.map((n) => n.link_url || null);
await this.db.query(query, [userIds, contents, linkUrls]);
} catch (error) {
handleDbError(
error,
logger,
'Database error in createBulkNotifications',
{ notifications },
{
fkMessage: 'One or more of the specified users do not exist.',
defaultMessage: 'Failed to create bulk notifications.',
},
);
}
}
/**
* Retrieves a paginated list of notifications for a specific user.
* @param userId The ID of the user whose notifications are to be retrieved.
* @param limit The maximum number of notifications to return.
* @param offset The number of notifications to skip for pagination.
* @returns A promise that resolves to an array of Notification objects.
*/
async getNotificationsForUser(
userId: string,
limit: number,
offset: number,
includeRead: boolean,
logger: Logger,
): Promise<Notification[]> {
try {
const params: (string | number)[] = [userId, limit, offset];
let query = `SELECT * FROM public.notifications WHERE user_id = $1`;
if (!includeRead) {
query += ` AND is_read = false`;
}
query += ` ORDER BY created_at DESC LIMIT $2 OFFSET $3`;
const res = await this.db.query<Notification>(query, params);
return res.rows;
} catch (error) {
handleDbError(
error,
logger,
'Database error in getNotificationsForUser',
{ userId, limit, offset, includeRead },
{ defaultMessage: 'Failed to retrieve notifications.' },
);
}
}
/**
* Gets the count of unread notifications for a specific user.
* This is optimized for the navbar badge UI.
* @param userId The ID of the user.
* @returns A promise that resolves to the count of unread notifications.
*/
async getUnreadCount(userId: string, logger: Logger): Promise<number> {
try {
const res = await this.db.query<{ count: string }>(
`SELECT COUNT(*) FROM public.notifications WHERE user_id = $1 AND is_read = false`,
[userId],
);
return parseInt(res.rows[0].count, 10);
} catch (error) {
handleDbError(
error,
logger,
'Database error in getUnreadCount',
{ userId },
{
defaultMessage: 'Failed to get unread notification count.',
},
);
}
}
/**
* Marks all unread notifications for a user as read.
* @param userId The ID of the user whose notifications should be marked as read.
* @returns A promise that resolves when the operation is complete.
*/
async markAllNotificationsAsRead(userId: string, logger: Logger): Promise<void> {
try {
await this.db.query(
`UPDATE public.notifications SET is_read = true WHERE user_id = $1 AND is_read = false`,
[userId],
);
} catch (error) {
handleDbError(
error,
logger,
'Database error in markAllNotificationsAsRead',
{ userId },
{
defaultMessage: 'Failed to mark notifications as read.',
},
);
}
}
/**
* Marks a single notification as read for a specific user.
* Ensures that a user can only mark their own notifications.
* @param notificationId The ID of the notification to mark as read.
* @param userId The ID of the user who owns the notification.
* @returns A promise that resolves to the updated Notification object.
* @throws An error if the notification is not found or does not belong to the user.
*/
async markNotificationAsRead(
notificationId: number,
userId: string,
logger: Logger,
): Promise<Notification> {
try {
const res = await this.db.query<Notification>(
`UPDATE public.notifications SET is_read = true WHERE notification_id = $1 AND user_id = $2 RETURNING *`,
[notificationId, userId],
);
if (res.rowCount === 0) {
throw new NotFoundError('Notification not found or user does not have permission.');
}
return res.rows[0];
} catch (error) {
handleDbError(
error,
logger,
'Database error in markNotificationAsRead',
{ notificationId, userId },
{ defaultMessage: 'Failed to mark notification as read.' },
);
}
}
/**
* Deletes a single notification for a specific user.
* Ensures that a user can only delete their own notifications.
* @param notificationId The ID of the notification to delete.
* @param userId The ID of the user who owns the notification.
* @throws NotFoundError if the notification is not found or does not belong to the user.
*/
async deleteNotification(notificationId: number, userId: string, logger: Logger): Promise<void> {
try {
const res = await this.db.query(
`DELETE FROM public.notifications WHERE notification_id = $1 AND user_id = $2`,
[notificationId, userId],
);
if (res.rowCount === 0) {
throw new NotFoundError('Notification not found or user does not have permission.');
}
} catch (error) {
handleDbError(
error,
logger,
'Database error in deleteNotification',
{ notificationId, userId },
{
defaultMessage: 'Failed to delete notification.',
},
);
}
}
/**
* Deletes notifications that are older than a specified number of days.
* This is intended for a periodic cleanup job.
* @param daysOld The minimum age in days for a notification to be deleted.
* @returns A promise that resolves to the number of deleted notifications.
*/
async deleteOldNotifications(daysOld: number, logger: Logger): Promise<number> {
try {
const res = await this.db.query(
`DELETE FROM public.notifications WHERE created_at < NOW() - ($1 * interval '1 day')`,
[daysOld],
);
return res.rowCount ?? 0;
} catch (error) {
handleDbError(
error,
logger,
'Database error in deleteOldNotifications',
{ daysOld },
{
defaultMessage: 'Failed to delete old notifications.',
},
);
}
}
}
|