eletrotupi / tcc/ api/src/controllers/sleepRecords.ts2d0189798624bc5481535444134dca1bb0fb1ee1
1.6 KB | 58 lines Raw
1
import { Request, Response, NextFunction } from 'express';
2
import { AuthenticatedRequest } from '@app/middleware/auth';
3
import {
4
  createSleepRecord,
5
  getSleepRecordsByUserId,
6
  destroySleepRecordById
7
} from '@app/services/sleepRecord.service';
8

9
import {
10
  CreateSleepRecordSchema
11
} from '@app/schemas'
12

13
export const SleepRecordsController = {
14
  create: async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
15
    try {
16
      const parsed = CreateSleepRecordSchema.safeParse(req.body.sleepRecord);
17

18
      if (!parsed.success) {
19
        return res.status(400).json({
20
          errors: parsed.error!.issues
21
        });
22
      }
23

24
      const sleepRecord = await createSleepRecord(req.userId!, parsed.data);
25

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

32
  index: async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
33
    try {
34
      const result = await getSleepRecordsByUserId(Number(req.userId), {
35
        limit: req.query.limit ? Number(req.query.limit) : undefined,
36
        page:  req.query.page  ? Number(req.query.page)  : undefined,
37
        from:  req.query.from  as string | undefined,
38
        to:    req.query.to    as string | undefined,
39
      });
40

41
      return res.status(200).json(
42
        result
43
      )
44
    } catch (err) {
45
      next(err);
46
    }
47
  },
48

49
  destroy: async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
50
    try {
51
      const result = await destroySleepRecordById(req.userId!, Number(req.params.id!));
52

53
      return res.status(200).json({})
54
    } catch (err) {
55
      next(err);
56
    }
57
  }
58
};