|
| 1 | +import { NextFunction, Request, Response } from 'express'; |
| 2 | +import { StatusCodes } from 'http-status-codes'; |
| 3 | +import { z } from 'zod'; |
| 4 | +import type { IUser } from '../interfaces/IUser'; |
| 5 | +import { NotificationEvent } from '../models/NotificationPreference'; |
| 6 | +import { notificationService } from '../services/notificationService'; |
| 7 | +import AppError from '../utils/AppError'; |
| 8 | + |
| 9 | +/** |
| 10 | + * NotificationController — HTTP surface for push notification preferences, |
| 11 | + * device registration and notification history. |
| 12 | + * |
| 13 | + * All routes operate on the authenticated user; none accept a user id from |
| 14 | + * the client, so one user can never read or mutate another's preferences. |
| 15 | + */ |
| 16 | + |
| 17 | +// ─── Validation schemas ──────────────────────────────────────────────────────── |
| 18 | + |
| 19 | +/** Body accepted by `PATCH /api/v1/notifications/preferences`. */ |
| 20 | +export const updatePreferencesSchema = z |
| 21 | + .object({ |
| 22 | + pushEnabled: z.boolean().optional(), |
| 23 | + enabledEvents: z.array(z.nativeEnum(NotificationEvent)).optional(), |
| 24 | + }) |
| 25 | + .refine((value) => value.pushEnabled !== undefined || value.enabledEvents !== undefined, { |
| 26 | + message: 'Provide at least one of "pushEnabled" or "enabledEvents"', |
| 27 | + }); |
| 28 | + |
| 29 | +/** Body accepted by `POST /api/v1/notifications/devices`. */ |
| 30 | +export const registerDeviceSchema = z.object({ |
| 31 | + token: z.string().trim().min(1, 'Device token is required').max(4096), |
| 32 | + platform: z.enum(['ios', 'android', 'web']), |
| 33 | +}); |
| 34 | + |
| 35 | +/** Body accepted by `DELETE /api/v1/notifications/devices`. */ |
| 36 | +export const unregisterDeviceSchema = z.object({ |
| 37 | + token: z.string().trim().min(1, 'Device token is required').max(4096), |
| 38 | +}); |
| 39 | + |
| 40 | +/** Query accepted by `GET /api/v1/notifications`. */ |
| 41 | +export const listNotificationsSchema = z.object({ |
| 42 | + page: z.coerce.number().int().min(1).default(1), |
| 43 | + limit: z.coerce.number().int().min(1).max(100).default(20), |
| 44 | +}); |
| 45 | + |
| 46 | +// ─── Helpers ─────────────────────────────────────────────────────────────────── |
| 47 | + |
| 48 | +/** |
| 49 | + * Resolve the authenticated user's id from the request. |
| 50 | + * |
| 51 | + * `authenticate` attaches the hydrated user document; this narrows it and |
| 52 | + * fails closed if the middleware was somehow bypassed. |
| 53 | + */ |
| 54 | +const requireUserId = (req: Request): string => { |
| 55 | + const user = (req as Request & { user?: IUser }).user; |
| 56 | + const id = user?._id ? String(user._id) : undefined; |
| 57 | + |
| 58 | + if (!id) { |
| 59 | + throw new AppError('Authentication required.', StatusCodes.UNAUTHORIZED); |
| 60 | + } |
| 61 | + return id; |
| 62 | +}; |
| 63 | + |
| 64 | +// ─── GET /api/v1/notifications/preferences ───────────────────────────────────── |
| 65 | + |
| 66 | +/** |
| 67 | + * Return the authenticated user's notification preferences. |
| 68 | + * |
| 69 | + * Defaults are created on first access, so this never 404s for a valid user. |
| 70 | + */ |
| 71 | +export const getPreferences = async ( |
| 72 | + req: Request, |
| 73 | + res: Response, |
| 74 | + next: NextFunction, |
| 75 | +): Promise<void> => { |
| 76 | + try { |
| 77 | + const preference = await notificationService.getPreferences(requireUserId(req)); |
| 78 | + |
| 79 | + res.status(StatusCodes.OK).json({ |
| 80 | + status: 'success', |
| 81 | + data: { |
| 82 | + pushEnabled: preference.pushEnabled, |
| 83 | + enabledEvents: preference.enabledEvents, |
| 84 | + deviceCount: preference.devices.length, |
| 85 | + }, |
| 86 | + }); |
| 87 | + } catch (error) { |
| 88 | + next(error); |
| 89 | + } |
| 90 | +}; |
| 91 | + |
| 92 | +// ─── PATCH /api/v1/notifications/preferences ─────────────────────────────────── |
| 93 | + |
| 94 | +/** |
| 95 | + * Update the authenticated user's notification preferences. |
| 96 | + * |
| 97 | + * Both fields are optional; `validateRequest` rejects an empty body. |
| 98 | + */ |
| 99 | +export const updatePreferences = async ( |
| 100 | + req: Request, |
| 101 | + res: Response, |
| 102 | + next: NextFunction, |
| 103 | +): Promise<void> => { |
| 104 | + try { |
| 105 | + const body = req.body as z.infer<typeof updatePreferencesSchema>; |
| 106 | + const preference = await notificationService.updatePreferences(requireUserId(req), body); |
| 107 | + |
| 108 | + res.status(StatusCodes.OK).json({ |
| 109 | + status: 'success', |
| 110 | + message: 'Notification preferences updated', |
| 111 | + data: { |
| 112 | + pushEnabled: preference.pushEnabled, |
| 113 | + enabledEvents: preference.enabledEvents, |
| 114 | + deviceCount: preference.devices.length, |
| 115 | + }, |
| 116 | + }); |
| 117 | + } catch (error) { |
| 118 | + next(error); |
| 119 | + } |
| 120 | +}; |
| 121 | + |
| 122 | +// ─── POST /api/v1/notifications/devices ──────────────────────────────────────── |
| 123 | + |
| 124 | +/** |
| 125 | + * Register (or refresh) a push token for one of the user's devices. |
| 126 | + * |
| 127 | + * Registering a token already held by another account detaches it from that |
| 128 | + * account first — see NotificationPreferenceRepository#registerDevice. |
| 129 | + */ |
| 130 | +export const registerDevice = async ( |
| 131 | + req: Request, |
| 132 | + res: Response, |
| 133 | + next: NextFunction, |
| 134 | +): Promise<void> => { |
| 135 | + try { |
| 136 | + const body = req.body as z.infer<typeof registerDeviceSchema>; |
| 137 | + const preference = await notificationService.registerDevice({ |
| 138 | + userId: requireUserId(req), |
| 139 | + token: body.token, |
| 140 | + platform: body.platform, |
| 141 | + }); |
| 142 | + |
| 143 | + res.status(StatusCodes.CREATED).json({ |
| 144 | + status: 'success', |
| 145 | + message: 'Device registered for push notifications', |
| 146 | + data: { deviceCount: preference.devices.length }, |
| 147 | + }); |
| 148 | + } catch (error) { |
| 149 | + next(error); |
| 150 | + } |
| 151 | +}; |
| 152 | + |
| 153 | +// ─── DELETE /api/v1/notifications/devices ────────────────────────────────────── |
| 154 | + |
| 155 | +/** Remove a device push token, e.g. on logout. */ |
| 156 | +export const unregisterDevice = async ( |
| 157 | + req: Request, |
| 158 | + res: Response, |
| 159 | + next: NextFunction, |
| 160 | +): Promise<void> => { |
| 161 | + try { |
| 162 | + const body = req.body as z.infer<typeof unregisterDeviceSchema>; |
| 163 | + const preference = await notificationService.unregisterDevice(requireUserId(req), body.token); |
| 164 | + |
| 165 | + res.status(StatusCodes.OK).json({ |
| 166 | + status: 'success', |
| 167 | + message: 'Device unregistered', |
| 168 | + data: { deviceCount: preference.devices.length }, |
| 169 | + }); |
| 170 | + } catch (error) { |
| 171 | + next(error); |
| 172 | + } |
| 173 | +}; |
| 174 | + |
| 175 | +// ─── GET /api/v1/notifications ───────────────────────────────────────────────── |
| 176 | + |
| 177 | +/** Return a page of the authenticated user's notification history. */ |
| 178 | +export const listNotifications = async ( |
| 179 | + req: Request, |
| 180 | + res: Response, |
| 181 | + next: NextFunction, |
| 182 | +): Promise<void> => { |
| 183 | + try { |
| 184 | + const { page, limit } = req.query as unknown as z.infer<typeof listNotificationsSchema>; |
| 185 | + const result = await notificationService.listForUser(requireUserId(req), page, limit); |
| 186 | + |
| 187 | + res.status(StatusCodes.OK).json({ |
| 188 | + status: 'success', |
| 189 | + data: result.data, |
| 190 | + pagination: { |
| 191 | + total: result.total, |
| 192 | + page: result.page, |
| 193 | + limit: result.limit, |
| 194 | + totalPages: result.totalPages, |
| 195 | + }, |
| 196 | + }); |
| 197 | + } catch (error) { |
| 198 | + next(error); |
| 199 | + } |
| 200 | +}; |
0 commit comments