Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

nsc-events_3_39_update-user-dto-refactor #42

Merged
merged 14 commits into from
Nov 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 37 additions & 37 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

71 changes: 0 additions & 71 deletions src/user/controllers/user/user.controller.spec.ts

This file was deleted.

24 changes: 5 additions & 19 deletions src/user/controllers/user/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,19 @@ import {
Get,
Param,
Patch,
Post,
Req,
UseGuards,
} from '@nestjs/common';
import { UserService } from '../../services/user/user.service';
import { Role } from '../../schemas/user.model';
import { CreateUserDto } from '../../dto/create-user.dto';
import { UserDocument } from '../../schemas/user.model';
import { AuthGuard } from '@nestjs/passport';
import { UpdateUserDto } from '../../dto/update-user.dto';

// ================== User admin routes ======================== \\
@Controller('users')
@UseGuards(AuthGuard('jwt'))
export class UserController {
constructor(private readonly userService: UserService) {}

// ----------------- Add User ------------------------------- \\
@Post('new')
async adminAddUser(@Body() createUserDto: CreateUserDto, @Req() req: any) {
const generatedId = await this.userService.newUser(createUserDto);
return { id: generatedId };
}

// ----------------- Get Users ----------------------------- \\
@Get('')
async getAllUsers() {
Expand All @@ -48,18 +39,13 @@ export class UserController {

// ----------------- Update User --------------------------- \\
@Patch('update/:id')
async updateUser(
@Param('id') id: string,
@Body('name') name: string,
@Body('email') email: string,
@Body('role') role: Role,
) {
await this.userService.updateUser(id, name, email, role);
async updateUser(@Param('id') id: string, @Body() userDto: UpdateUserDto) {
return await this.userService.updateUser(id, userDto as UserDocument);
}

// ----------------- Delete User --------------------------- //
@Delete('remove/:id')
async adminDeleteUser(@Param('id') id: string, @Req() req: any) {
async adminDeleteUser(@Param('id') id: string) {
await this.userService.removeUser(id);
}

Expand Down
20 changes: 20 additions & 0 deletions src/user/dto/update-user.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { IsEmpty, IsEnum, IsOptional, IsString } from 'class-validator';
import { Role } from '../schemas/user.model';

export class UpdateUserDto {
@IsOptional()
@IsString()
readonly name: string;

@IsOptional()
@IsEmpty({ message: 'Cannot update email here' })
readonly email: string;

@IsOptional()
@IsEmpty({ message: 'Cannot update password here' })
readonly password: string;

@IsOptional()
@IsEnum(Role)
readonly role: Role;
}
73 changes: 28 additions & 45 deletions src/user/services/user/user.service.ts
Original file line number Diff line number Diff line change
@@ -1,45 +1,20 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
import {
BadRequestException,
ForbiddenException,
HttpException,
HttpStatus,
Injectable,
NotFoundException,
UnauthorizedException,
} from '@nestjs/common';
import * as bcrypt from 'bcryptjs';
import { Model } from 'mongoose';
import { Role, UserDocument } from '../../schemas/user.model';
import { UserDocument } from '../../schemas/user.model';
import { InjectModel } from '@nestjs/mongoose';
import { CreateUserDto } from 'src/user/dto/create-user.dto';
import { log } from 'console';

@Injectable()
export class UserService {
constructor(@InjectModel('User') private userModel: Model<UserDocument>) {
// User defined in user.module.ts
}

// ----------------- Add user ----------------- \\
async newUser(createUserDto: CreateUserDto): Promise<string> {
const { name, email, password, role } = createUserDto;
const hashedPassword = await bcrypt.hash(password, 10);
const newUser = new this.userModel({
name,
email,
password: hashedPassword,
role,
});
try {
const result = await newUser.save();
return result._id;
} catch (error) {
log(error);
return error;
}
}

// ----------------- Get all users ----------------- \\
async getAllUsers(): Promise<any> {
//fix: Use serialization to mask password, so we don't have to transform the data
Expand Down Expand Up @@ -84,30 +59,38 @@ export class UserService {
if (!user) {
throw new HttpException('User not found!', 404);
}

return user;
return {
id: user.id,
name: user.name,
email: user.email,
role: user.role,
} as UserDocument;
}

// ----------------- Update user ----------------- \\
async updateUser(id: string, name: string, email: string, role: Role) {
const updatedUser = await this.userModel.findById(id).exec();
if (!updatedUser) {
throw new NotFoundException('User not found');
}

if (name) {
updatedUser.name = name;
async updateUser(id: string, user: UserDocument) {
// we may want to check if id is a valid id, if you remove/add a character, it returns a 500 error
if (user === null) {
throw new BadRequestException(`Updated User not supplied`);
}
if (email) {
updatedUser.email = email;
}
if (role) {
updatedUser.role = role;
const updatedUser = await this.userModel
.findByIdAndUpdate(id, user, {
new: true,
runValidators: true,
})
.exec();
if (!updatedUser) {
throw new HttpException(
`User with id ${id} not found`,
HttpStatus.NOT_FOUND,
);
}

const updated = await updatedUser.save();
console.log(updated);
return updated;
return {
id: updatedUser.id,
name: updatedUser.name,
email: updatedUser.email,
role: updatedUser.role,
} as UserDocument;
}

// ----------------- Delete user ----------------- \\
Expand Down