eletrotupi / tcc/ api/src/controllers/moods.ts6b0e21c082d83d67530667a986f1cd80d982458e
2.8 KB | 103 lines Raw
1
import { Request, Response, NextFunction } from 'express';
2
import { AuthenticatedRequest } from '@app/middleware/auth';
3
import { User } from '@prisma/client';
4
import {
5
  createMood,
6
  getMoodsByUserId,
7
  getMoodById,
8
  destroyMoodById
9
} from '@app/services/mood.service';
10

11
import { findUsersElligibleForPush } from '@app/services/user.service';
12
import { sendPushNotification } from '@app/lib/sendPushNotification';
13

14
import {
15
  CreateMoodSchema
16
} from '@app/schemas'
17
import { formatValidationError } from '@app/lib/errors/validationError'
18

19
export const MoodsController = {
20
  create: async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
21
    try {
22
      const parsed = CreateMoodSchema.safeParse(req.body.mood);
23

24
      if (!parsed.success) {
25
        return res.status(400).json(formatValidationError(parsed.error!));
26
      }
27

28
      const mood = await createMood(req.userId!, parsed.data);
29

30
      return res.status(201).json({ mood });
31
    } catch (err) {
32
      next(err);
33
    }
34
  },
35

36
  index: async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
37
    try {
38
      const result = await getMoodsByUserId(Number(req.userId), {
39
        limit: req.query.limit ? Number(req.query.limit) : undefined,
40
        page:  req.query.page  ? Number(req.query.page)  : undefined,
41
        from:  req.query.from  as string | undefined,
42
        to:    req.query.to    as string | undefined,
43
      });
44

45
      return res.status(200).json(
46
        result
47
      )
48
    } catch (err) {
49
      next(err);
50
    }
51
  },
52

53
  show: async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
54
    try {
55
      const mood = await getMoodById(Number(req.params.id));
56

57
      if (!mood) {
58
        return res.status(404).json({ errors: "Mood was not found" });
59
      }
60

61
      return res.status(200).json(
62
        mood
63
      );
64
    } catch (err) {
65
      next(err);
66
    }
67
  },
68

69
  destroy: async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
70
    try {
71
      const result = await destroyMoodById(req.userId!, Number(req.params.id!));
72

73
      return res.status(200).json({})
74
    } catch (err) {
75
      next(err);
76
    }
77
  },
78

79
  sendNotification: async (req: Request, res: Response, next: NextFunction) => {
80
    try {
81
      const users = await findUsersElligibleForPush();
82

83
      if (users) {
84
        await Promise.all(
85
          users
86
            .filter((user: User) => user.pushToken)
87
            .map((user: User) =>
88
              sendPushNotification({
89
                token: user.pushToken!,
90
                title: 'Como você está?',
91
                body: 'Adicione mais registros de humor.',
92
                data: { screen: 'notifications' },
93
              })
94
            )
95
        );
96
      }
97

98
      return res.status(200).json(users)
99
    } catch (err) {
100
      next(err);
101
    }
102
  }
103
};