Skip to content

Commit

Permalink
Refactor: Updated routes and controllers structure, migrated database…
Browse files Browse the repository at this point in the history
…, added new validations and fields, and fixed bugs
  • Loading branch information
maxCastro1 committed May 1, 2024
1 parent cb3e7bd commit 4c98039
Show file tree
Hide file tree
Showing 6 changed files with 186 additions and 29 deletions.
24 changes: 24 additions & 0 deletions migrations/1714495123940-users.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { MigrationInterface, QueryRunner } from "typeorm";

export class CreateUserMigration1614495123940 implements MigrationInterface {

public async up(queryRunner: QueryRunner): Promise<void> {

Check warning on line 5 in migrations/1714495123940-users.ts

View workflow job for this annotation

GitHub Actions / build-lint-test-coverage

Missing space before function parentheses

Check warning on line 5 in migrations/1714495123940-users.ts

View workflow job for this annotation

GitHub Actions / build-lint-test-coverage

Missing space before function parentheses
await queryRunner.query(`
CREATE TABLE "user" (
"id" SERIAL NOT NULL,
"firstName" character varying NOT NULL,
"lastName" character varying NOT NULL,
"email" character varying NOT NULL,
"password" character varying NOT NULL,
"userType" character varying NOT NULL DEFAULT 'Buyer',
CONSTRAINT "UQ_e12875dfb3b1d92d7d7c5377e22" UNIQUE ("email"),
CONSTRAINT "PK_cace4a159ff9f2512dd42373760" PRIMARY KEY ("id")
)
`);
}

public async down(queryRunner: QueryRunner): Promise<void> {

Check warning on line 20 in migrations/1714495123940-users.ts

View workflow job for this annotation

GitHub Actions / build-lint-test-coverage

Missing space before function parentheses

Check warning on line 20 in migrations/1714495123940-users.ts

View workflow job for this annotation

GitHub Actions / build-lint-test-coverage

Missing space before function parentheses
await queryRunner.query(`DROP TABLE "user"`);
}

}
31 changes: 31 additions & 0 deletions migrations/1714553873264-UpdateUserEntity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { MigrationInterface, QueryRunner } from "typeorm";

export class CreateUserMigration1614495123940 implements MigrationInterface {

public async up(queryRunner: QueryRunner): Promise<void> {

Check warning on line 5 in migrations/1714553873264-UpdateUserEntity.ts

View workflow job for this annotation

GitHub Actions / build-lint-test-coverage

Missing space before function parentheses

Check warning on line 5 in migrations/1714553873264-UpdateUserEntity.ts

View workflow job for this annotation

GitHub Actions / build-lint-test-coverage

Missing space before function parentheses
await queryRunner.query(`
CREATE TABLE "user" (
"id" uuid NOT NULL DEFAULT uuid_generate_v4(),
"firstName" character varying NOT NULL,
"lastName" character varying NOT NULL,
"email" character varying NOT NULL,
"password" character varying NOT NULL,
"gender" character varying NOT NULL,
"phoneNumber" character varying NOT NULL,
"photoUrl" character varying,
"verified" boolean NOT NULL,
"status" character varying NOT NULL CHECK (status IN ('active', 'suspended')),
"userType" character varying NOT NULL DEFAULT 'Buyer' CHECK (userType IN ('Admin', 'Buyer', 'Vendor')),
"createdAt" TIMESTAMP NOT NULL DEFAULT now(),
"updatedAt" TIMESTAMP NOT NULL DEFAULT now(),
CONSTRAINT "UQ_e12875dfb3b1d92d7d7c5377e22" UNIQUE ("email"),
CONSTRAINT "PK_cace4a159ff9f2512dd42373760" PRIMARY KEY ("id")
)
`);
}

public async down(queryRunner: QueryRunner): Promise<void> {

Check warning on line 27 in migrations/1714553873264-UpdateUserEntity.ts

View workflow job for this annotation

GitHub Actions / build-lint-test-coverage

Missing space before function parentheses

Check warning on line 27 in migrations/1714553873264-UpdateUserEntity.ts

View workflow job for this annotation

GitHub Actions / build-lint-test-coverage

Missing space before function parentheses
await queryRunner.query(`DROP TABLE "user"`);
}

}
51 changes: 51 additions & 0 deletions src/controllers/authController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { Request, Response } from 'express';
import { User } from '../entities/User';;

Check warning on line 2 in src/controllers/authController.ts

View workflow job for this annotation

GitHub Actions / build-lint-test-coverage

Unnecessary semicolon

Check warning on line 2 in src/controllers/authController.ts

View workflow job for this annotation

GitHub Actions / build-lint-test-coverage

Unnecessary semicolon
import bcrypt from 'bcrypt';
import { getRepository } from 'typeorm';


class UserController {
static registerUser = async (req: Request, res: Response) => {

Check warning on line 8 in src/controllers/authController.ts

View workflow job for this annotation

GitHub Actions / build-lint-test-coverage

Missing return type on function

Check warning on line 8 in src/controllers/authController.ts

View workflow job for this annotation

GitHub Actions / build-lint-test-coverage

Missing return type on function
const { firstName, lastName, email, password, gender, phoneNumber, userType, status, verified, photoUrl } = req.body;



// Validate user input
if (!(firstName && lastName && email && password && gender && phoneNumber && verified && photoUrl)) {
return res.status(400).json({ error: 'Please fill all the fields' });
}

const userRepository = getRepository(User);


// Check for existing user
const existingUser = await userRepository.findOneBy({ email });
const existingUserNumber = await userRepository.findOneBy({ phoneNumber });

if (existingUser || existingUserNumber) {
return res.status(400).json({ error: 'Email or phone number already in use' });
}

const saltRounds = 10;
const hashedPassword = await bcrypt.hash(password, saltRounds);

// Create user
const user = new User();
user.firstName = firstName;
user.lastName = lastName;
user.email = email;
user.password = hashedPassword;
user.userType = userType;
user.gender = gender;
user.phoneNumber = phoneNumber;
user.photoUrl = photoUrl;
user.status = status ? status : 'active';
user.verified = verified;

// Save user
await userRepository.save(user);

return res.status(201).json({ message: 'User registered successfully' });
};
}
export { UserController };
69 changes: 69 additions & 0 deletions src/entities/User.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
Unique,
CreateDateColumn,
UpdateDateColumn,
} from 'typeorm';
import { IsEmail, IsNotEmpty, IsString, IsBoolean, IsIn } from 'class-validator';

@Entity()
@Unique(['email'])
export class User {
@PrimaryGeneratedColumn('uuid')
@IsNotEmpty()
id!: string;

@Column()
@IsNotEmpty()
@IsString()
firstName!: string;

@Column()
@IsNotEmpty()
@IsString()
lastName!: string;

@Column()
@IsNotEmpty()
@IsEmail()
email!: string;

@Column()
@IsNotEmpty()
password!: string;

@Column()
@IsNotEmpty()
@IsString()
gender!: string;

@Column()
@IsNotEmpty()
phoneNumber!: string;

@Column({ nullable: true })
photoUrl?: string;

@Column()
@IsNotEmpty()
@IsBoolean()
verified!: boolean;

@Column()
@IsNotEmpty()
@IsIn(['active', 'suspended'])
status!: 'active' | 'suspended';

@Column({ default: "Buyer" })
@IsNotEmpty()
@IsIn(['Admin', 'Buyer', 'Vendor'])
userType!: 'Admin' | 'Buyer' | 'Vendor';

@CreateDateColumn()
createdAt!: Date;

@UpdateDateColumn()
updatedAt!: Date;
}
29 changes: 0 additions & 29 deletions src/entity/User.ts

This file was deleted.

11 changes: 11 additions & 0 deletions src/routes/UserRoutes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Router } from 'express';
import { UserController } from '../controllers/index';


const { registerUser } = UserController;

const router = Router();

router.post('/register', registerUser);

export default router;

0 comments on commit 4c98039

Please sign in to comment.