71 lines
2.0 KiB
TypeScript
71 lines
2.0 KiB
TypeScript
// 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;
|
|
|
|
@ApiOkResponse({
|
|
type: LoginRes,
|
|
})
|
|
@Post('/login')
|
|
async login(@Body() body) {
|
|
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 }) {
|
|
const { username, password } = body;
|
|
try {
|
|
await this.userService.addUser(username, password);
|
|
return successResponse(true);
|
|
} catch (error) {
|
|
console.log(error);
|
|
return errorResponse('添加用户失败');
|
|
}
|
|
}
|
|
|
|
@Get('/list')
|
|
async listUsers(@Query() query: { current: number; pageSize: number }) {
|
|
const { current = 1, pageSize = 10 } = query;
|
|
return successResponse(await this.userService.listUsers(current, pageSize));
|
|
}
|
|
|
|
@Post('/toggleActive')
|
|
async toggleActive(@Body() body: { userId: number; isActive: boolean }) {
|
|
return this.userService.toggleUserActive(body.userId, body.isActive);
|
|
}
|
|
|
|
@ApiOkResponse()
|
|
@Get()
|
|
async getUser(@User() user) {
|
|
try {
|
|
return successResponse(await this.userService.getUser(user.id));
|
|
} catch (error) {
|
|
return errorResponse('获取失败');
|
|
}
|
|
}
|
|
}
|