| 1 | import { Request, Response, NextFunction } from 'express';
|
| 2 | import { AuthenticatedRequest } from '@app/middleware/auth';
|
| 3 | import {
|
| 4 | createSleepRecord,
|
| 5 | getSleepRecordsByUserId,
|
| 6 | destroySleepRecordById,
|
| 7 | getSleepRecordById,
|
| 8 | updateSleepRecordById
|
| 9 | } from '@app/services/sleepRecord.service';
|
| 10 |
|
| 11 | import {
|
| 12 | CreateSleepRecordSchema,
|
| 13 | UpdateSleepRecordSchema
|
| 14 | } from '@app/schemas'
|
| 15 | import { formatValidationError } from '@app/lib/errors/validationError'
|
| 16 |
|
| 17 | export const SleepRecordsController = {
|
| 18 | create: async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
|
| 19 | try {
|
| 20 | const parsed = CreateSleepRecordSchema.safeParse(req.body.sleepRecord);
|
| 21 |
|
| 22 | if (!parsed.success) {
|
| 23 | return res.status(400).json(formatValidationError(parsed.error!));
|
| 24 | }
|
| 25 |
|
| 26 | const sleepRecord = await createSleepRecord(req.userId!, parsed.data);
|
| 27 |
|
| 28 | return res.status(201).json({ sleepRecord });
|
| 29 | } catch (err) {
|
| 30 | next(err);
|
| 31 | }
|
| 32 | },
|
| 33 |
|
| 34 | index: async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
|
| 35 | try {
|
| 36 | const result = await getSleepRecordsByUserId(Number(req.userId), {
|
| 37 | limit: req.query.limit ? Number(req.query.limit) : undefined,
|
| 38 | page: req.query.page ? Number(req.query.page) : undefined,
|
| 39 | from: req.query.from as string | undefined,
|
| 40 | to: req.query.to as string | undefined,
|
| 41 | });
|
| 42 |
|
| 43 | return res.status(200).json(
|
| 44 | result
|
| 45 | )
|
| 46 | } catch (err) {
|
| 47 | next(err);
|
| 48 | }
|
| 49 | },
|
| 50 |
|
| 51 | show: async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
|
| 52 | try {
|
| 53 | const sleepRecord = await getSleepRecordById(Number(req.userId!), Number(req.params.id!));
|
| 54 |
|
| 55 | return res.status(200).json(sleepRecord)
|
| 56 | } catch (err) {
|
| 57 | next(err);
|
| 58 | }
|
| 59 | },
|
| 60 |
|
| 61 | destroy: async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
|
| 62 | try {
|
| 63 | const result = await destroySleepRecordById(req.userId!, Number(req.params.id!));
|
| 64 |
|
| 65 | return res.status(200).json({})
|
| 66 | } catch (err) {
|
| 67 | next(err);
|
| 68 | }
|
| 69 | },
|
| 70 |
|
| 71 | update: async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
|
| 72 | try {
|
| 73 | const parsed = UpdateSleepRecordSchema.safeParse(req.body.sleepRecord);
|
| 74 |
|
| 75 | if (!parsed.success) {
|
| 76 | return res.status(400).json(formatValidationError(parsed.error!));
|
| 77 | }
|
| 78 |
|
| 79 | const sleepRecord = await updateSleepRecordById(req.userId!, Number(req.params.id!), parsed.data);
|
| 80 |
|
| 81 | return res.status(200).json({ sleepRecord });
|
| 82 | } catch (err) {
|
| 83 | next(err);
|
| 84 | }
|
| 85 | }
|
| 86 | };
|