admin.controller.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { Body, Controller, Del, Get, Inject, Param, Post, Put, Query } from '@midwayjs/core';
  2. import { AdminService } from '../../service/system/admin.service';
  3. import { get, omit, pick } from 'lodash';
  4. import { ApiResponse, ApiTags } from '@midwayjs/swagger';
  5. import { BaseController } from '../../frame/BaseController';
  6. import { ErrorCode, ServiceError } from '../../error/service.error';
  7. import { Validate } from '@midwayjs/validate';
  8. import { CVO_admin, FVO_admin, QVO_admin, UVAO_admin } from '../../interface/system/admin.interface';
  9. import * as bcrypt from 'bcryptjs';
  10. const namePrefix = '管理用户';
  11. @ApiTags(['管理用户表'])
  12. @Controller('/admin', { tagName: namePrefix })
  13. export class HomeController implements BaseController {
  14. controllerCode = 'user_admin';
  15. @Inject()
  16. service: AdminService;
  17. @Get('/')
  18. @ApiTags('列表查询')
  19. @ApiResponse({ type: QVO_admin })
  20. async index(@Query() query: object) {
  21. const qobj = omit(query, ['skip', 'limit']);
  22. const others = pick(query, ['skip', 'limit']);
  23. const result = await this.service.query(qobj, others);
  24. return result;
  25. }
  26. @Get('/:id')
  27. @ApiTags('单查询')
  28. @ApiResponse({ type: FVO_admin })
  29. async fetch(@Param('id') id: number) {
  30. const data = await this.service.fetch({ id });
  31. const result = new FVO_admin(data);
  32. return result;
  33. }
  34. @Post('/', { routerName: `创建${namePrefix}` })
  35. @ApiTags('创建数据')
  36. @Validate()
  37. @ApiResponse({ type: CVO_admin })
  38. async create(@Body() data: object) {
  39. // 处理密码
  40. const passowrd = get(data, 'password');
  41. if (passowrd) {
  42. const salt = bcrypt.genSaltSync(10);
  43. const hash = bcrypt.hashSync(passowrd, salt);
  44. Object.assign(data, { password: hash });
  45. }
  46. const result = await this.service.create(data);
  47. return result;
  48. }
  49. @Post('/:id', { routerName: `修改${namePrefix}` })
  50. @ApiTags('修改数据')
  51. @Validate()
  52. @ApiResponse({ type: UVAO_admin })
  53. async update(@Param('id') id: number, @Body() data: object) {
  54. if (!id) throw new ServiceError(ErrorCode.ID_NOT_FOUND);
  55. data = omit(data, ['password']);
  56. const result = await this.service.update({ id }, data);
  57. return result;
  58. }
  59. @Del('/:id', { routerName: `删除${namePrefix}` })
  60. @ApiTags('删除数据')
  61. @Validate()
  62. async delete(@Param('id') id: number) {
  63. const result = await this.service.delete({ id });
  64. return result;
  65. }
  66. @Put('/init')
  67. async init() {
  68. await this.service.initSuperAdmin();
  69. return 'ok';
  70. }
  71. }