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

refactor(be): improve client user & notice module error handling logic #2119

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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
38 changes: 8 additions & 30 deletions apps/backend/apps/client/src/notice/notice.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,16 @@ import {
Get,
Query,
Param,
NotFoundException,
InternalServerErrorException,
Logger,
DefaultValuePipe,
ParseBoolPipe
} from '@nestjs/common'
import { Prisma } from '@prisma/client'
import { AuthNotNeededIfOpenSpace } from '@libs/auth'
import { CursorValidationPipe, GroupIDPipe, RequiredIntPipe } from '@libs/pipe'
import { NoticeService } from './notice.service'

@Controller('notice')
@AuthNotNeededIfOpenSpace()
export class NoticeController {
private readonly logger = new Logger(NoticeController.name)

constructor(private readonly noticeService: NoticeService) {}

@Get()
Expand All @@ -30,36 +24,20 @@ export class NoticeController {
@Query('fixed', new DefaultValuePipe(false), ParseBoolPipe) fixed: boolean,
@Query('search') search?: string
) {
try {
return await this.noticeService.getNotices({
cursor,
take,
fixed,
search,
groupId
})
} catch (error) {
this.logger.error(error)
throw new InternalServerErrorException()
}
return await this.noticeService.getNotices({
cursor,
take,
fixed,
search,
groupId
})
}

@Get(':id')
async getNoticeByID(
@Query('groupId', GroupIDPipe) groupId: number,
@Param('id', new RequiredIntPipe('id')) id: number
) {
try {
return await this.noticeService.getNoticeByID(id, groupId)
} catch (error) {
if (
error instanceof Prisma.PrismaClientKnownRequestError &&
error.name === 'NotFoundError'
) {
throw new NotFoundException(error.message)
}
this.logger.error(error)
throw new InternalServerErrorException()
}
return await this.noticeService.getNoticeByID(id, groupId)
}
}
44 changes: 22 additions & 22 deletions apps/backend/apps/client/src/notice/notice.service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Injectable } from '@nestjs/common'
import { OPEN_SPACE_ID } from '@libs/constants'
import { EntityNotExistException } from '@libs/exception'
import { PrismaService } from '@libs/prisma'

@Injectable()
Expand All @@ -20,7 +21,6 @@ export class NoticeService {
groupId?: number
}) {
const paginator = this.prisma.getPaginator(cursor)

const notices = await this.prisma.notice.findMany({
...paginator,
where: {
Expand Down Expand Up @@ -53,7 +53,6 @@ export class NoticeService {
createdBy: notice.createdBy?.username
}
})

const total = await this.prisma.notice.count({
where: {
groupId,
Expand All @@ -70,28 +69,29 @@ export class NoticeService {
}

async getNoticeByID(id: number, groupId = OPEN_SPACE_ID) {
const current = await this.prisma.notice
.findUniqueOrThrow({
where: {
id,
groupId,
isVisible: true
},
select: {
title: true,
content: true,
createTime: true,
updateTime: true,
createdBy: {
select: {
username: true
}
const notice = await this.prisma.notice.findUnique({
where: {
id,
groupId,
isVisible: true
},
select: {
title: true,
content: true,
createTime: true,
updateTime: true,
createdBy: {
select: {
username: true
}
}
})
.then((notice) => {
return { ...notice, createdBy: notice.createdBy?.username }
})
}
})

if (!notice) {
throw new EntityNotExistException('notice')
}
const current = { ...notice, createdBy: notice.createdBy?.username }

const navigate = (pos: 'prev' | 'next') => {
type Order = 'asc' | 'desc'
Expand Down
34 changes: 2 additions & 32 deletions apps/backend/apps/client/src/user/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,11 @@ import {
Req,
Res,
Controller,
Logger,
Delete,
Query,
NotFoundException,
InternalServerErrorException
Query
} from '@nestjs/common'
import { Prisma } from '@prisma/client'
import { Request, type Response } from 'express'
import { AuthenticatedRequest, AuthNotNeededIfOpenSpace } from '@libs/auth'
import {
EntityNotExistException,
UnidentifiedException,
UnprocessableDataException
} from '@libs/exception'
import { DeleteUserDto } from './dto/deleteUser.dto'
import { EmailAuthenticationPinDto } from './dto/email-auth-pin.dto'
import { NewPasswordDto } from './dto/newPassword.dto'
Expand All @@ -33,8 +24,6 @@ import { UserService } from './user.service'

@Controller('user')
export class UserController {
private readonly logger = new Logger(UserController.name)

constructor(private readonly userService: UserService) {}

@Patch('password-reset')
Expand Down Expand Up @@ -96,32 +85,13 @@ export class UserController {
@Req() req: AuthenticatedRequest,
@Body() updateUserDto: UpdateUserDto
) {
try {
return await this.userService.updateUser(req, updateUserDto)
} catch (error) {
if (
error instanceof Prisma.PrismaClientKnownRequestError &&
error.name == 'NotFoundError'
) {
throw new NotFoundException(error.message)
} else if (
error instanceof EntityNotExistException ||
error instanceof UnprocessableDataException ||
error instanceof UnidentifiedException
) {
throw error.convert2HTTPException()
}
this.logger.error(error)
throw new InternalServerErrorException()
}
return await this.userService.updateUser(req, updateUserDto)
}
}

@Controller('email-auth')
@AuthNotNeededIfOpenSpace()
export class EmailAuthenticationController {
private readonly logger = new Logger(EmailAuthenticationController.name)

constructor(private readonly userService: UserService) {}

setJwtInHeader(res: Response, jwt: string) {
Expand Down
30 changes: 17 additions & 13 deletions apps/backend/apps/client/src/user/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -583,6 +583,7 @@ export class UserService {
if (!this.isValidPassword(updateUserDto.newPassword)) {
throw new UnprocessableDataException('Bad new password')
}

encryptedNewPassword = await hash(
updateUserDto.newPassword,
ARGON2_HASH_OPTION
Expand All @@ -598,20 +599,23 @@ export class UserService {
}
}

const updatedUser = await this.prisma.user.update({
where: { id: req.user.id },
data: updateData,
select: {
// don't select password for security
studentId: true,
major: true,
userProfile: {
select: {
realName: true
try {
return await this.prisma.user.update({
where: { id: req.user.id },
data: updateData,
select: {
// don't select password for security
studentId: true,
major: true,
userProfile: {
select: {
realName: true
}
}
}
}
})
return updatedUser
})
} catch (error) {
throw new UnprocessableDataException(error.message)
}
}
}
Loading