feat(用户): 添加用户信息更新接口
新增用户信息更新功能,支持修改用户名、密码、权限和角色字段 添加用户名唯一性校验和密码加密处理
This commit is contained in:
parent
6855b13ed7
commit
7b3c7540d7
|
|
@ -62,6 +62,23 @@ export class UserController {
|
|||
return this.userService.toggleUserActive(body.userId, body.isActive);
|
||||
}
|
||||
|
||||
// 中文注释:更新用户(支持用户名/密码/权限/角色更新)
|
||||
@Post('/update/:id')
|
||||
async updateUser(
|
||||
@Body() body: { username?: string; password?: string; isSuper?: boolean; isAdmin?: boolean; permissions?: string[] },
|
||||
@Query('id') id?: number
|
||||
) {
|
||||
try {
|
||||
// 条件判断:优先从路径参数获取 ID(兼容生成的 API 文件为 POST /user/update/:id)
|
||||
const userId = Number((this.ctx?.params?.id ?? id));
|
||||
if (!userId) throw new Error('缺少用户ID');
|
||||
const data = await this.userService.updateUser(userId, body);
|
||||
return successResponse(data);
|
||||
} catch (error) {
|
||||
return errorResponse(error?.message || '更新失败');
|
||||
}
|
||||
}
|
||||
|
||||
@ApiOkResponse()
|
||||
@Get()
|
||||
async getUser(@User() user) {
|
||||
|
|
|
|||
|
|
@ -113,6 +113,44 @@ export class UserService {
|
|||
return this.userModel.save(user);
|
||||
}
|
||||
|
||||
// 中文注释:更新用户信息(支持用户名唯一校验与可选密码修改)
|
||||
async updateUser(
|
||||
userId: number,
|
||||
payload: {
|
||||
username?: string;
|
||||
password?: string;
|
||||
isSuper?: boolean;
|
||||
isAdmin?: boolean;
|
||||
permissions?: string[];
|
||||
}
|
||||
) {
|
||||
// 条件判断:查询用户是否存在
|
||||
const user = await this.userModel.findOne({ where: { id: userId } });
|
||||
if (!user) {
|
||||
throw new Error('User not found');
|
||||
}
|
||||
|
||||
// 条件判断:若提供了新用户名且与原用户名不同,校验唯一性
|
||||
if (payload.username && payload.username !== user.username) {
|
||||
const exist = await this.userModel.findOne({ where: { username: payload.username } });
|
||||
if (exist) throw new Error('用户名已存在');
|
||||
user.username = payload.username;
|
||||
}
|
||||
|
||||
// 条件判断:若提供密码则进行加密存储
|
||||
if (payload.password) {
|
||||
user.password = await bcrypt.hash(payload.password, 10);
|
||||
}
|
||||
|
||||
// 条件判断:更新布尔与权限字段(若提供则覆盖)
|
||||
if (typeof payload.isSuper === 'boolean') user.isSuper = payload.isSuper;
|
||||
if (typeof payload.isAdmin === 'boolean') user.isAdmin = payload.isAdmin;
|
||||
if (Array.isArray(payload.permissions)) user.permissions = payload.permissions;
|
||||
|
||||
// 保存更新
|
||||
return await this.userModel.save(user);
|
||||
}
|
||||
|
||||
async getUser(userId: number) {
|
||||
return plainToInstance(
|
||||
User,
|
||||
|
|
|
|||
Loading…
Reference in New Issue