eletrotupi / tcc/ api/src/controllers/insights.tsc901c35af9c84b6a29e5185545ced1129f33b8f4
1.5 KB | 52 lines Raw
1
import { Response, NextFunction } from "express";
2
import { AuthenticatedRequest } from "@app/middleware/auth";
3
import { InsightType } from "@prisma/client";
4
import { getInsightsByUserId } from "@app/services/insight.service";
5
import { parseAppDay } from "@app/lib/queue/processors/insights/utils";
6
import { InsightsQuerySchema } from "@app/schemas";
7
import { formatValidationError } from "@app/lib/errors/validationError";
8

9
const DAILY_INSIGHT_TYPES = new Set<InsightType>([
10
  InsightType.DAILY_ENERGY,
11
  InsightType.DAILY_SLEEP,
12
]);
13

14
// A day with no explicit date means "today" for the daily insight types, so the
15
// client never computes a day boundary; other types stay unfiltered
16
function resolveInsightDay(
17
  type?: InsightType,
18
  day?: string,
19
): Date | undefined {
20
  if (day) return parseAppDay(day);
21

22
  return type && DAILY_INSIGHT_TYPES.has(type) ? new Date() : undefined;
23
}
24

25
export const InsightsController = {
26
  index: async (
27
    req: AuthenticatedRequest,
28
    res: Response,
29
    next: NextFunction,
30
  ) => {
31
    try {
32
      const parsedQuery = InsightsQuerySchema.safeParse(req.query);
33

34
      if (!parsedQuery.success) {
35
        return res.status(400).json(formatValidationError(parsedQuery.error));
36
      }
37

38
      const { type, period, limit, day } = parsedQuery.data;
39

40
      const insights = await getInsightsByUserId(req.userId!, {
41
        type,
42
        period,
43
        limit,
44
        day: resolveInsightDay(type, day),
45
      });
46

47
      return res.status(200).json({ insights });
48
    } catch (err) {
49
      next(err);
50
    }
51
  },
52
};