// src/controller/user.controller.ts import { Controller, Post, Get, Body, Query } from '@midwayjs/core'; import { Inject } from '@midwayjs/decorator'; import { UserService } from '../service/user.service'; import { errorResponse, successResponse } from '../utils/response.util'; import { ApiOkResponse } from '@midwayjs/swagger'; import { BooleanRes, LoginRes } from '../dto/reponse.dto'; import { User } from '../decorator/user.decorator'; @Controller('/user') export class UserController { @Inject() userService: UserService; @Inject() ctx; @ApiOkResponse({ type: LoginRes, }) @Post('/login') async login(@Body() body) { this.ctx.logger.info('ip:', this.ctx.ip, '; path:', this.ctx.path, '; user:', body?.username); try { const result = await this.userService.login(body); return successResponse(result, '登录成功'); } catch (error) { return errorResponse(error?.message || '登录失败', error?.code); } } @ApiOkResponse({ type: BooleanRes, }) @Post('/logout') async logout() { // 可选:在这里处理服务端缓存的 token 或 session return successResponse(true); } @Post('/add') async addUser(@Body() body: { username: string; password: string; email?: string; remark?: string }) { const { username, password, email, remark } = body; try { // 新增用户 支持邮箱与备注 await this.userService.addUser(username, password, remark, email); return successResponse(true); } catch (error) { console.log(error); return errorResponse('添加用户失败'); } } @Get('/list') async listUsers( @Query() query: { current: number; pageSize: number; remark?: string; username?: string; email?: string; isActive?: string; isSuper?: string; isAdmin?: string; sortField?: string; sortOrder?: string; } ) { const { current = 1, pageSize = 10, remark, username, email, isActive, isSuper, isAdmin, sortField, sortOrder } = query; // 将字符串布尔转换为真实布尔 const toBool = (v?: string) => (v === undefined ? undefined : v === 'true'); // 处理排序方向 const order = (sortOrder === 'ascend' || sortOrder === 'ASC') ? 'ASC' : 'DESC'; // 列表移除密码字段 const { items, total } = await this.userService.listUsers( current, pageSize, { remark, username, email, isActive: toBool(isActive), isSuper: toBool(isSuper), isAdmin: toBool(isAdmin), }, { field: sortField, order, } ); const safeItems = (items || []).map((it: any) => { const { password, ...rest } = it || {}; return rest; }); return successResponse({ items: safeItems, total, current, pageSize }); } @Post('/toggleActive') async toggleActive(@Body() body: { userId: number; isActive: boolean }) { try { // 调用服务层更新启用状态 const data = await this.userService.toggleUserActive(body.userId, body.isActive); // 移除密码字段,保证安全 const { password, ...safe } = data as any; return successResponse(safe); } catch (error) { return errorResponse(error?.message || '操作失败'); } } // 更新用户(支持用户名/密码/权限/角色更新) @Post('/update/:id') async updateUser( @Body() body: { username?: string; password?: string; email?: string; isSuper?: boolean; isAdmin?: boolean; permissions?: string[]; remark?: 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); // 移除密码字段,保证安全 const { password, ...safe } = data as any; return successResponse(safe); } catch (error) { return errorResponse(error?.message || '更新失败'); } } @ApiOkResponse() @Get() async getUser(@User() user) { try { // 详情移除密码字段 const data = await this.userService.getUser(user.id); const { password, ...safe } = (data as any) || {}; return successResponse(safe); } catch (error) { return errorResponse('获取失败'); } } }