api: add mood delete endpoint

Pedro Lucas Porcellis porcellis@eletrotupi.com 1 month ago 1228979c846b33d8390ecbbd7fd746acc32df67a
Parents: 1ae4e10
5 file(s) changed
  • api/prisma/migrations/20260518044632_add_cascade_to_mood_components/migration.sql +5 -0
  • api/prisma/schema.prisma +1 -1
  • api/src/controllers/moods.ts +15 -4
  • api/src/routes/moods.ts +1 -0
  • api/src/services/mood.service.ts +9 -0
api/prisma/migrations/20260518044632_add_cascade_to_mood_components/migration.sql
@@ -0,0 +1,5 @@
1 + -- DropForeignKey
2 + ALTER TABLE "mood_components" DROP CONSTRAINT "mood_components_mood_id_fkey";
3 +
4 + -- AddForeignKey
5 + ALTER TABLE "mood_components" ADD CONSTRAINT "mood_components_mood_id_fkey" FOREIGN KEY ("mood_id") REFERENCES "moods"("id") ON DELETE CASCADE ON UPDATE CASCADE;
api/prisma/schema.prisma
@@ -51,7 +51,7 @@ component MoodComponentOption
51 51 intensity IntensityLevel @default(LIGHT)
52 52
53 53 moodId Int @map("mood_id")
54 - mood Mood @relation(fields: [moodId], references: [id])
54 + mood Mood @relation(fields: [moodId], references: [id], onDelete: Cascade)
55 55
56 56 @@map("mood_components")
57 57 }
api/src/controllers/moods.ts
@@ -3,7 +3,8 @@ import { AuthenticatedRequest } from '@app/middleware/auth';
3 3 import {
4 4 createMood,
5 5 getMoodsByUserId,
6 - getMoodById
6 + getMoodById,
7 + destroyMoodById
7 8 } from '@app/services/mood.service';
8 9
9 10 import {
@@ -48,15 +49,25 @@ },
48 49
49 50 show: async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
50 51 try {
51 - const mood = await getMoodById(Number(req.params.id))
52 + const mood = await getMoodById(Number(req.params.id));
52 53
53 54 if (!mood) {
54 - return res.status(404).json({ errors: "not found" })
55 + return res.status(404).json({ errors: "Mood was not found" });
55 56 }
56 57
57 58 return res.status(200).json(
58 59 mood
59 - )
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({})
60 71 } catch (err) {
61 72 next(err);
62 73 }
api/src/routes/moods.ts
@@ -7,5 +7,6 @@
7 7 router.get('/', requireAuth, MoodsController.index);
8 8 router.get('/:id', requireAuth, MoodsController.show);
9 9 router.post('/', requireAuth, MoodsController.create);
10 + router.delete('/:id', requireAuth, MoodsController.destroy);
10 11
11 12 export default router;
api/src/services/mood.service.ts
@@ -70,3 +70,12 @@ },
70 70 include: { moodComponents: true }
71 71 });
72 72 }
73 +
74 + export const destroyMoodById = async (userId: number, id: number): Promise<Mood> => {
75 + return await prisma.mood.delete({
76 + where: {
77 + id,
78 + userId
79 + }
80 + })
81 + }