| 1 | import { Response, NextFunction } from 'express';
|
| 2 | import { AuthenticatedRequest } from '@app/middleware/auth';
|
| 3 | import {
|
| 4 | createMood,
|
| 5 | getMoodsByUserId,
|
| 6 | getMoodById,
|
| 7 | destroyMoodById
|
| 8 | } from '@app/services/mood.service';
|
| 9 |
|
| 10 | import {
|
| 11 | CreateMoodSchema
|
| 12 | } from '@app/schemas'
|
| 13 | import { formatValidationError } from '@app/lib/errors/validationError'
|
| 14 |
|
| 15 | export const MoodsController = {
|
| 16 | create: async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
|
| 17 | try {
|
| 18 | const parsed = CreateMoodSchema.safeParse(req.body.mood);
|
| 19 |
|
| 20 | if (!parsed.success) {
|
| 21 | return res.status(400).json(formatValidationError(parsed.error!));
|
| 22 | }
|
| 23 |
|
| 24 | const mood = await createMood(req.userId!, parsed.data);
|
| 25 |
|
| 26 | return res.status(201).json({ mood });
|
| 27 | } catch (err) {
|
| 28 | next(err);
|
| 29 | }
|
| 30 | },
|
| 31 |
|
| 32 | index: async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
|
| 33 | try {
|
| 34 | const result = await getMoodsByUserId(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 | show: async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
|
| 50 | try {
|
| 51 | const mood = await getMoodById(Number(req.params.id));
|
| 52 |
|
| 53 | if (!mood) {
|
| 54 | return res.status(404).json({ errors: "Mood was not found" });
|
| 55 | }
|
| 56 |
|
| 57 | return res.status(200).json(
|
| 58 | mood
|
| 59 | );
|
| 60 | } catch (err) {
|
| 61 | next(err);
|
| 62 | }
|
| 63 | },
|
| 64 |
|
| 65 | destroy: async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
|
| 66 | try {
|
| 67 | const result = await destroyMoodById(req.userId!, Number(req.params.id!));
|
| 68 |
|
| 69 | return res.status(200).json({})
|
| 70 | } catch (err) {
|
| 71 | next(err);
|
| 72 | }
|
| 73 | }
|
| 74 | };
|