-
Notifications
You must be signed in to change notification settings - Fork 1
/
cycles.ts
65 lines (55 loc) · 1.77 KB
/
cycles.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { and, eq, gte, lte } from 'drizzle-orm';
import type { Request, Response } from 'express';
import * as schema from '../db/schema';
import { GetCycleById, getCycleVotes } from '../services/cycles';
import { NodePgDatabase } from 'drizzle-orm/node-postgres';
export function getActiveCyclesHandler(dbPool: NodePgDatabase<typeof schema>) {
return async function (req: Request, res: Response) {
const activeCycles = await dbPool.query.cycles.findMany({
where: and(lte(schema.cycles.startAt, new Date()), gte(schema.cycles.endAt, new Date())),
with: {
questions: {
with: {
options: {
columns: {
voteScore: false,
},
where: eq(schema.options.show, true),
},
},
},
},
});
return res.json({ data: activeCycles });
};
}
export function getCycleHandler(dbPool: NodePgDatabase<typeof schema>) {
return async function (req: Request, res: Response) {
const { cycleId } = req.params;
if (!cycleId) {
return res.status(400).json({ error: 'Missing cycleId' });
}
const out = await GetCycleById(dbPool, cycleId);
return res.json({ data: out });
};
}
/**
* Handler to receive the votes for a specific cycle and user.
*/
export function getCycleVotesHandler(dbPool: NodePgDatabase<typeof schema>) {
return async function (req: Request, res: Response) {
const userId = req.session.userId;
const cycleId = req.params.cycleId;
if (!cycleId) {
return res.status(400).json({
errors: [
{
message: 'Expected cycleId in query params',
},
],
});
}
const votesRow = await getCycleVotes(dbPool, userId, cycleId);
return res.json({ data: votesRow });
};
}