| 1 | import { Request, Response, NextFunction } from 'express';
|
| 2 | import {
|
| 3 | findUserById,
|
| 4 | findUserByEmail,
|
| 5 | updateUser,
|
| 6 | generateToken
|
| 7 | } from '@app/models/user';
|
| 8 |
|
| 9 | import {
|
| 10 | validateRequiredFields
|
| 11 | } from '@app/utils/validators'
|
| 12 |
|
| 13 | import { getQueue, MailJobName } from '@app/lib/queue';
|
| 14 | import {
|
| 15 | CreateUserSchema
|
| 16 | } from '@app/schemas';
|
| 17 |
|
| 18 | import {
|
| 19 | createUser
|
| 20 | } from '@app/services/user.service';
|
| 21 |
|
| 22 | export const UsersController = {
|
| 23 | create: async (req: Request, res: Response, next: NextFunction) => {
|
| 24 | try {
|
| 25 | const parsed = CreateUserSchema.safeParse(req.body.user);
|
| 26 |
|
| 27 | if (!parsed.success) {
|
| 28 | return res.status(422).json({
|
| 29 | errors: parsed.error!.issues
|
| 30 | })
|
| 31 | }
|
| 32 |
|
| 33 | const user = await createUser(parsed.data);
|
| 34 | const jwtToken = generateToken(user.id, user.email);
|
| 35 |
|
| 36 | const mailQueue = getQueue('mail');
|
| 37 | const job = await mailQueue.add(MailJobName.WelcomeEmail, { userId: user.id });
|
| 38 |
|
| 39 | res.status(201).json({
|
| 40 | token: jwtToken
|
| 41 | });
|
| 42 | } catch (err) {
|
| 43 | next(err);
|
| 44 | }
|
| 45 | },
|
| 46 |
|
| 47 | update: async (req: Request, res: Response, next: NextFunction) => {
|
| 48 | try {
|
| 49 | const { id } = req.params
|
| 50 | const { user: userParams } = req.body;
|
| 51 |
|
| 52 | if (userParams) {
|
| 53 | const { email, password, firstName, lastName } = userParams;
|
| 54 |
|
| 55 | const user = await findUserById(Number(id));
|
| 56 |
|
| 57 | if (!user) {
|
| 58 | return res.status(404).json({
|
| 59 | error: "Usuário não encontrado"
|
| 60 | })
|
| 61 | }
|
| 62 |
|
| 63 | if (email || password || firstName || lastName) {
|
| 64 | const response = await updateUser(user, {
|
| 65 | email, firstName, lastName, password
|
| 66 | })
|
| 67 |
|
| 68 | const updated = await findUserById(Number(id))
|
| 69 |
|
| 70 | // TODO: Drop encrypted password & token here
|
| 71 | return res.status(200).json({
|
| 72 | user: updated
|
| 73 | })
|
| 74 | } else {
|
| 75 | return res.status(200).json({
|
| 76 | user
|
| 77 | })
|
| 78 | }
|
| 79 | }
|
| 80 | } catch (err) {
|
| 81 | next(err);
|
| 82 | }
|
| 83 | }
|
| 84 | };
|