forked from Predictify-org/predictify-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnotifications.ts
More file actions
183 lines (165 loc) · 4.69 KB
/
Copy pathnotifications.ts
File metadata and controls
183 lines (165 loc) · 4.69 KB
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
import {
Router,
type Request,
} from "express";
import { z } from "zod";
import { logger } from "../config/logger";
import { requireAuth } from "../middleware/requireAuth";
import {
getNotificationPreferences,
notificationCategories,
notificationChannels,
patchNotificationPreferences,
} from "../services/notificationPrefs";
import { markNotificationsAsRead } from "../services/notificationService";
import { idempotency } from "../middleware/idempotency";
import { RouteErrorFactory } from "../errors";
import { notificationsCors } from "../middleware/cors";
import { notificationsMetricsMiddleware } from "../metrics/notificationsMetrics";
const notificationCategorySchema = z.enum(notificationCategories);
const notificationChannelSchema = z.enum(notificationChannels);
const patchPreferencesBodySchema = z
.object({
preferences: z
.array(
z
.object({
category: notificationCategorySchema,
channel: notificationChannelSchema,
enabled: z.boolean(),
})
.strict(),
)
.min(1),
})
.strict();
const uuidSchema = z.string().uuid();
const markReadBodySchema = z
.object({
notificationIds: z.array(uuidSchema).optional(),
markAllAsRead: z.boolean().optional(),
})
.strict()
.refine(
(data) => (data.notificationIds?.length ?? 0) > 0 || data.markAllAsRead === true,
{
message: "Either notificationIds (non-empty array) or markAllAsRead=true is required",
path: ["notificationIds"],
},
);
export const notificationsRouter = Router();
// Enforce CORS allowlist early so unapproved origins are rejected
// before any processing (preflight responses cached via Access-Control-Max-Age).
notificationsRouter.use(notificationsCors());
notificationsRouter.use(requireAuth);
notificationsRouter.use(notificationsMetricsMiddleware);
notificationsRouter.get(
"/preferences",
async (req, res, next) => {
try {
const userId = (req as Request & { user: { id: string } }).user.id;
const preferences = await getNotificationPreferences(userId);
logger.info(
{
reqId: (req as Request & { id?: string }).id,
userId,
preferenceCount: preferences.length,
},
"notification_preferences_loaded",
);
return res.status(200).json({
data: {
preferences,
},
});
} catch (error) {
return next(error);
}
},
);
notificationsRouter.patch(
"/preferences",
idempotency,
async (req, res, next) => {
const parsed = patchPreferencesBodySchema.safeParse(req.body);
if (!parsed.success) {
logger.warn(
{
reqId: (req as Request & { id?: string }).id,
issues: parsed.error.issues,
},
"notification_preferences_validation_failed",
);
return next(RouteErrorFactory.validation("Invalid request body"));
}
try {
const userId = (req as Request & { user: { id: string } }).user.id;
const preferences = await patchNotificationPreferences(
userId,
parsed.data.preferences,
);
logger.info(
{
reqId: (req as Request & { id?: string }).id,
userId,
updatedCount: parsed.data.preferences.length,
},
"notification_preferences_updated",
);
return res.status(200).json({
data: {
preferences,
},
});
} catch (error) {
return next(error);
}
},
);
notificationsRouter.post(
"/mark-read",
idempotency,
async (req: Request, res: Response, next: NextFunction) => {
const parsed = markReadBodySchema.safeParse(req.body);
if (!parsed.success) {
logger.warn(
{
reqId: (req as Request & { id?: string }).id,
issues: parsed.error.issues,
},
"notifications_mark_read_validation_failed",
);
return res.status(400).json({
error: {
code: "validation_error",
details: parsed.error.issues,
},
});
}
try {
const userId = (req as Request & { user: { id: string } }).user.id;
const { notificationIds, markAllAsRead } = parsed.data;
const result = await markNotificationsAsRead({
userId,
notificationIds,
markAllAsRead,
});
logger.info(
{
reqId: (req as Request & { id?: string }).id,
userId,
updatedCount: result.updatedCount,
markAllAsRead: markAllAsRead ?? false,
},
"notifications_marked_read",
);
return res.status(200).json({
data: {
updatedCount: result.updatedCount,
},
});
} catch (error) {
return next(error);
}
},
);