eletrotupi / tcc/ api/src/controllers/careActions.tsd139cd140eae38d7f5b7000fa39a09c78d163f07
2.2 KB | 74 lines Raw
1
import { Response, NextFunction } from 'express';
2
import { AuthenticatedRequest } from '@app/middleware/auth';
3
import { CareActionType } from '@prisma/client';
4
import { CreateCareActionSchema } from '@app/schemas';
5
import {
6
  getCareActionsByUserId,
7
  getCareActionById,
8
  createCareAction,
9
  destroyCareActionById,
10
} from '@app/services/careAction.service';
11

12
export const CareActionsController = {
13
  index: async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
14
    try {
15
      const result = await getCareActionsByUserId(Number(req.userId), {
16
        type: req.query.type as CareActionType | undefined,
17
        from: req.query.from as string | undefined,
18
        to: req.query.to as string | undefined,
19
        limit: req.query.limit ? Number(req.query.limit) : undefined,
20
        page: req.query.page ? Number(req.query.page) : undefined,
21
      });
22

23
      return res.status(200).json(result);
24
    } catch (err) {
25
      next(err);
26
    }
27
  },
28

29
  show: async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
30
    try {
31
      const careAction = await getCareActionById(
32
        Number(req.userId),
33
        Number(req.params.id),
34
      );
35

36
      if (!careAction) {
37
        return res.status(404).json({ errors: 'Care action was not found' });
38
      }
39

40
      return res.status(200).json({ careAction });
41
    } catch (err) {
42
      next(err);
43
    }
44
  },
45

46
  create: async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
47
    try {
48
      const parsed = CreateCareActionSchema.safeParse(req.body.careAction);
49

50
      req.log.info("Params: %s", req.body.careAction)
51
      req.log.info("Care action: %s", parsed.error)
52

53
      if (!parsed.success) {
54
        return res.status(400).json({ errors: parsed.error!.issues });
55
      }
56

57
      const careAction = await createCareAction(req.userId!, parsed.data);
58

59
      return res.status(201).json({ careAction });
60
    } catch (err) {
61
      next(err);
62
    }
63
  },
64

65
  destroy: async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
66
    try {
67
      await destroyCareActionById(req.userId!, Number(req.params.id));
68

69
      return res.status(200).json({});
70
    } catch (err) {
71
      next(err);
72
    }
73
  },
74
};