api: create users + model services
Parents:
abfe26d2 file(s) changed
- api/src/controllers/users.ts +39 -0
- api/src/models/user.ts +50 -0
api/src/controllers/users.ts
@@ -0,0 +1,39 @@
1 + import { Request, Response, NextFunction } from 'express';
2 + import {
3 + createUser,
4 + generateToken
5 + } from '@app/models/user';
6 +
7 + import {
8 + validateRequiredFields
9 + } from '@app/utils/validators'
10 +
11 + export const UsersController = {
12 + create: async (req: Request, res: Response, next: NextFunction) => {
13 + try {
14 + const { email, password, first_name: firstName, last_name: lastName } = req.body;
15 +
16 + // Validate required fields
17 + const requiredValidation = validateRequiredFields(req.body, [
18 + 'email', 'password', 'first_name'
19 + ]);
20 +
21 + if (!requiredValidation.valid) {
22 + return res.status(400).json({
23 + error: "Campos faltantes",
24 + missing: requiredValidation.missing
25 + });
26 + }
27 +
28 + const user = await createUser(
29 + email, firstName, lastName, password
30 + );
31 +
32 + const jwtToken = generateToken(user.id);
33 +
34 + res.status(201).json({ token: jwtToken });
35 + } catch (err) {
36 + next(err);
37 + }
38 + }
39 + };
api/src/models/user.ts
@@ -0,0 +1,50 @@
1 + import bcrypt from "bcryptjs";
2 + import { prisma } from '../lib/prisma'
3 +
4 + import {
5 + isValidEmail,
6 + isValidPassword,
7 + sanitizeString,
8 + validateRequiredFields
9 + } from "@app/utils/validators";
10 +
11 + import { InvalidEmailError, ShortPasswordError } from '@app/lib/errors/UserErrors'
12 +
13 + const createUser = async (email: string, firstName: string, lastName: string, password: string) => {
14 + // Validate email format
15 + if (!isValidEmail(email)) {
16 + throw new InvalidEmailError()
17 + }
18 +
19 + // Validate password strength
20 + if (!isValidPassword(password)) {
21 + throw new ShortPasswordError()
22 + }
23 +
24 + const encryptedPassword = bcrypt.hashSync(password, 10);
25 +
26 + try {
27 + const user = await prisma.user.create({
28 + data: {
29 + email,
30 + firstName,
31 + lastName,
32 + encryptedPassword
33 + }
34 + });
35 +
36 + return user;
37 + } catch (err: any) {
38 + console.log(err)
39 + throw new Error("Something was off when creating user")
40 + }
41 + }
42 +
43 + const generateToken = (userId: number) => {
44 + return 'xxx' + userId
45 + }
46 +
47 + export {
48 + createUser,
49 + generateToken
50 + }