-
Notifications
You must be signed in to change notification settings - Fork 1
/
votes.ts
48 lines (40 loc) · 1.46 KB
/
votes.ts
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
import type { Request, Response } from 'express';
import { z } from 'zod';
import * as schema from '../db/schema';
import { validateAndSaveVotes, updateOptionScore } from '../services/votes';
import { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { logger } from '../utils/logger';
/**
* Handler function that saves votes submitted by a user.
*/
export function saveVotesHandler(dbPool: NodePgDatabase<typeof schema>) {
return async function (req: Request, res: Response) {
const userId = req.session.userId;
const reqBody = z
.array(
z.object({
optionId: z.string(),
numOfVotes: z.number().min(0),
}),
)
.safeParse(req.body);
if (!reqBody.success) {
return res.status(400).json({ errors: reqBody.error.errors });
}
// Insert votes
try {
const voteResults = await validateAndSaveVotes(dbPool, reqBody.data, userId);
if (voteResults.errors && voteResults.errors.length > 0) {
return res.status(400).json({ errors: voteResults.errors });
}
const optionScores = await updateOptionScore(dbPool, reqBody.data, voteResults.questionIds);
if (optionScores.errors && optionScores.errors.length > 0) {
return res.status(400).json({ errors: optionScores.errors });
}
return res.json({ data: optionScores.data });
} catch (e) {
logger.error(`error saving votes: ${e}`);
return res.status(500).json({ errors: e });
}
};
}