优化后端,实现前端添加用户

This commit is contained in:
2025-05-12 13:29:29 +08:00
parent 805901767c
commit 74f874109c
6 changed files with 141 additions and 8 deletions

View File

@@ -32,7 +32,16 @@ export class AdminUserController {
async create(
@Body() createDto: CreateDto
) {
return this.userService.create(createDto);
return this.userService.create({
...createDto,
...createDto.password && (() => {
const salt = this.userService.generateSalt();
return {
salt,
password_hash: this.userService.hashPassword(createDto.password, salt),
}
})(),
});
}
@Put(':userId')

View File

@@ -1,4 +1,4 @@
import { IsString, Length, ValidateIf } from "class-validator";
import { IsString, Length, Matches, ValidateIf } from "class-validator";
export class CreateDto {
@ValidateIf(o => o.username !== null)
@@ -6,18 +6,24 @@ export class CreateDto {
@Length(6, 32, { message: '用户名长度只能为6~32' })
username: string | null;
@ValidateIf(o => o.username !== null)
@ValidateIf(o => o.nickname !== null)
@IsString({ message: '昵称不得为空' })
@Length(6, 30, { message: '昵称长度只能为6~30' })
nickname: string | null;
@ValidateIf(o => o.username !== null)
@ValidateIf(o => o.email !== null)
@IsString({ message: '邮箱不得为空' })
@Length(6, 254, { message: '邮箱长度只能为6~254' })
email: string | null;
@ValidateIf(o => o.username !== null)
@ValidateIf(o => o.phone !== null)
@IsString({ message: '手机号不得为空' })
@Length(11, 11, { message: '手机号长度只能为11' })
phone: string | null;
@ValidateIf(o => o.password !== null)
@IsString({ message: '密码不得为空' })
@Length(6, 32)
@Matches(/^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d!@#$%^&*()_+\-=\[\]{};:'",.<>/?]{6,32}$/)
password: string | null;
}

View File

@@ -22,8 +22,15 @@ export class UserService {
}
async create(user: Partial<User>): Promise<User> {
const newUser = this.userRepository.create(user);
return this.userRepository.save(newUser);
try {
const newUser = this.userRepository.create(user);
return this.userRepository.save(newUser);
} catch (error) {
if (error instanceof QueryFailedError) {
throw new ConflictException(this.getDuplicateErrorMessage(error));
}
throw new BadRequestException('创建用户失败');
}
}
async update(userId: string, user: Partial<User>): Promise<User> {