eletrotupi / tcc/ api/src/controllers/insights.ts16a7e33e5e723f45548ed5cc1b9959317ff3a683
935 B | 31 lines Raw
1
import { Response, NextFunction } from "express";
2
import { AuthenticatedRequest } from "@app/middleware/auth";
3
import { getInsightsByUserId } from "@app/services/insight.service";
4
import { InsightsQuerySchema } from "@app/schemas";
5
import { formatValidationError } from "@app/lib/errors/validationError";
6

7
export const InsightsController = {
8
  index: async (
9
    req: AuthenticatedRequest,
10
    res: Response,
11
    next: NextFunction,
12
  ) => {
13
    try {
14
      const parsedQuery = InsightsQuerySchema.safeParse(req.query);
15

16
      if (!parsedQuery.success) {
17
        return res.status(400).json(formatValidationError(parsedQuery.error));
18
      }
19

20
      const insights = await getInsightsByUserId(req.userId!, {
21
        type: parsedQuery.data.type,
22
        period: parsedQuery.data.period,
23
        limit: parsedQuery.data.limit,
24
      });
25

26
      return res.status(200).json({ insights });
27
    } catch (err) {
28
      next(err);
29
    }
30
  },
31
};