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

[backend] Use class serializer interceptor #29

Merged
merged 4 commits into from
Nov 6, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
5 changes: 3 additions & 2 deletions backend/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { HttpAdapterHost, NestFactory } from '@nestjs/core';
import { HttpAdapterHost, NestFactory, Reflector } from '@nestjs/core';
import { AppModule } from './app.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { ValidationPipe } from '@nestjs/common';
import { ClassSerializerInterceptor, ValidationPipe } from '@nestjs/common';
import { PrismaClientExceptionFilter } from 'nestjs-prisma';

async function bootstrap() {
Expand All @@ -10,6 +10,7 @@ async function bootstrap() {
app.setGlobalPrefix('api');

app.useGlobalPipes(new ValidationPipe({ whitelist: true })); // enable validation
app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector))); // enable serialization

const config = new DocumentBuilder()
.setTitle('Pong API')
Expand Down
6 changes: 6 additions & 0 deletions backend/src/user/entities/user.entity.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import { User } from '@prisma/client';
import { ApiProperty } from '@nestjs/swagger';
import { Exclude } from 'class-transformer';

export class UserEntity implements User {
constructor(partial: Partial<UserEntity>) {
Object.assign(this, partial);
}

@ApiProperty()
id: number;

Expand All @@ -11,5 +16,6 @@ export class UserEntity implements User {
@ApiProperty({ required: false, nullable: true })
name: string | null;

@Exclude()
password: string;
}
26 changes: 15 additions & 11 deletions backend/src/user/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
Patch,
Param,
Delete,
HttpCode,
ParseIntPipe,
} from '@nestjs/common';
import { UserService } from './user.service';
Expand All @@ -27,34 +28,37 @@ export class UserController {

@Post()
@ApiCreatedResponse({ type: UserEntity })
create(@Body() createUserDto: CreateUserDto) {
return this.userService.create(createUserDto);
async create(@Body() createUserDto: CreateUserDto): Promise<UserEntity> {
const user = await this.userService.create(createUserDto);
return new UserEntity(user);
}

@Get()
@ApiOkResponse({ type: [UserEntity] })
findAll() {
return this.userService.findAll();
async findAll(): Promise<UserEntity[]> {
const users = await this.userService.findAll();
return users.map((user) => new UserEntity(user));
}

@Get(':id')
@ApiOkResponse({ type: UserEntity })
findOne(@Param('id', ParseIntPipe) id: number) {
return this.userService.findOne(+id);
async findOne(@Param('id', ParseIntPipe) id: number): Promise<UserEntity> {
return new UserEntity(await this.userService.findOne(id));
}

@Patch(':id')
@ApiOkResponse({ type: UserEntity })
update(
async update(
@Param('id', ParseIntPipe) id: number,
@Body() updateUserDto: UpdateUserDto,
) {
return this.userService.update(+id, updateUserDto);
): Promise<UserEntity> {
return new UserEntity(await this.userService.update(id, updateUserDto));
}

@Delete(':id')
@HttpCode(204)
@ApiNoContentResponse()
remove(@Param('id', ParseIntPipe) id: number) {
return this.userService.remove(+id);
async remove(@Param('id', ParseIntPipe) id: number): Promise<void> {
await this.userService.remove(id);
}
}
48 changes: 15 additions & 33 deletions backend/src/user/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,53 +5,35 @@ import { PrismaService } from 'src/prisma/prisma.service';
import { User, Prisma } from '@prisma/client';
import { hash } from 'bcrypt';

type UserWithoutPassword = Omit<User, 'password'>;

function excludePassword(user: User): Omit<User, 'password'> {
const { password, ...userWithoutPassword } = user;
return userWithoutPassword;
}

@Injectable()
export class UserService {
constructor(private prisma: PrismaService) {}

async create(createUserDto: CreateUserDto): Promise<UserWithoutPassword> {
async create(createUserDto: CreateUserDto): Promise<User> {
const saltRounds = 10;
const hashedPassword = await hash(createUserDto.password, saltRounds);
const userData = { ...createUserDto, password: hashedPassword };
return this.prisma.user.create({ data: userData }).then(excludePassword);
return this.prisma.user.create({ data: userData });
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The password hashing logic is still present in the create method. Consider moving it to a separate function for better modularity and reusability. This will also make the code easier to test and maintain.

+  async hashPassword(password: string): Promise<string> {
+    const saltRounds = 10;
+    return await hash(password, saltRounds);
+  }

-  async create(createUserDto: CreateUserDto): Promise<User> {
-    const saltRounds = 10;
-    const hashedPassword = await hash(createUserDto.password, saltRounds);
-    const userData = { ...createUserDto, password: hashedPassword };
-    return this.prisma.user.create({ data: userData });
-  }

+  async create(createUserDto: CreateUserDto): Promise<User> {
+    const hashedPassword = await this.hashPassword(createUserDto.password);
+    const userData = { ...createUserDto, password: hashedPassword };
+    return this.prisma.user.create({ data: userData });
+  }

Commitable suggestion

[!IMPORTANT]
Carefully review the code before committing. Make sure it correctly replaces the highlighted code, has no missing lines and indentaion issues.

Suggested change
async create(createUserDto: CreateUserDto): Promise<User> {
const saltRounds = 10;
const hashedPassword = await hash(createUserDto.password, saltRounds);
const userData = { ...createUserDto, password: hashedPassword };
return this.prisma.user.create({ data: userData }).then(excludePassword);
return this.prisma.user.create({ data: userData });
}
async hashPassword(password: string): Promise<string> {
const saltRounds = 10;
return await hash(password, saltRounds);
}
async create(createUserDto: CreateUserDto): Promise<User> {
const hashedPassword = await this.hashPassword(createUserDto.password);
const userData = { ...createUserDto, password: hashedPassword };
return this.prisma.user.create({ data: userData });
}


findAll(): Promise<UserWithoutPassword[]> {
return this.prisma.user
.findMany()
.then((users) => users.map(excludePassword));
findAll(): Promise<User[]> {
return this.prisma.user.findMany();
}

findOne(id: number): Promise<UserWithoutPassword> {
return this.prisma.user
.findUniqueOrThrow({ where: { id: id } })
.then(excludePassword);
findOne(id: number): Promise<User> {
return this.prisma.user.findUniqueOrThrow({ where: { id: id } });
}

update(
id: number,
updateUserDto: UpdateUserDto,
): Promise<UserWithoutPassword> {
return this.prisma.user
.update({
where: { id: id },
data: updateUserDto,
})
.then(excludePassword);
update(id: number, updateUserDto: UpdateUserDto): Promise<User> {
return this.prisma.user.update({
where: { id: id },
data: updateUserDto,
});
}

remove(id: number): Promise<UserWithoutPassword> {
return this.prisma.user
.delete({
where: { id: id },
})
.then(excludePassword);
remove(id: number): Promise<User> {
return this.prisma.user.delete({
where: { id: id },
});
}
}