| 1 | import { Request, 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 |
|
| 14 | export const MoodsController = {
|
| 15 | create: async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
|
| 16 | try {
|
| 17 | const parsed = CreateMoodSchema.safeParse(req.body.mood);
|
| 18 |
|
| 19 | if (!parsed.success) {
|
| 20 | return res.status(400).json({
|
| 21 | errors: parsed.error!.issues
|
| 22 | });
|
| 23 | }
|
| 24 |
|
| 25 | const mood = await createMood(req.userId!, parsed.data);
|
| 26 |
|
| 27 | return res.status(201).json({ mood });
|
| 28 | } catch (err) {
|
| 29 | next(err);
|
| 30 | }
|
| 31 | },
|
| 32 |
|
| 33 | index: async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
|
| 34 | try {
|
| 35 | const result = await getMoodsByUserId(Number(req.userId), {
|
| 36 | limit: req.query.limit ? Number(req.query.limit) : undefined,
|
| 37 | page: req.query.page ? Number(req.query.page) : undefined,
|
| 38 | from: req.query.from as string | undefined,
|
| 39 | to: req.query.to as string | undefined,
|
| 40 | });
|
| 41 |
|
| 42 | return res.status(200).json(
|
| 43 | result
|
| 44 | )
|
| 45 | } catch (err) {
|
| 46 | next(err);
|
| 47 | }
|
| 48 | },
|
| 49 |
|
| 50 | show: async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
|
| 51 | try {
|
| 52 | const mood = await getMoodById(Number(req.params.id));
|
| 53 |
|
| 54 | if (!mood) {
|
| 55 | return res.status(404).json({ errors: "Mood was not found" });
|
| 56 | }
|
| 57 |
|
| 58 | return res.status(200).json(
|
| 59 | mood
|
| 60 | );
|
| 61 | } catch (err) {
|
| 62 | next(err);
|
| 63 | }
|
| 64 | },
|
| 65 |
|
| 66 | destroy: async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
|
| 67 | try {
|
| 68 | const result = await destroyMoodById(req.userId!, Number(req.params.id!));
|
| 69 |
|
| 70 | return res.status(200).json({})
|
| 71 | } catch (err) {
|
| 72 | next(err);
|
| 73 | }
|
| 74 | }
|
| 75 | };
|