1
0

base.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { Controller } from 'egg';
  2. import { IHelper } from '../../typings/app';
  3. export interface ResOp {
  4. data?: any;
  5. code?: number;
  6. message?: string;
  7. }
  8. /**
  9. * @apiDefine BaseRes
  10. * @apiSuccess {Number} code 错误码,成功则返回200
  11. * @apiSuccess {String} message 错误信息,成功则返回success
  12. * @apiSuccess {Object} data 返回的数据
  13. */
  14. /**
  15. * @apiDefine Auth
  16. * @apiHeader {String} Authorization 管理员登陆Token
  17. */
  18. /**
  19. * @apiDefine Page
  20. * @apiSuccess {Array} data.list 查询数据列表
  21. * @apiSuccess {Object} data.pagination 分页信息
  22. * @apiSuccess {Number} data.pagination.page 当前页数
  23. * @apiSuccess {Number} data.pagination.size 限制个数
  24. * @apiSuccess {Number} data.pagination.total 总数量
  25. */
  26. export default abstract class BaseController extends Controller {
  27. /**
  28. * 获取Query
  29. */
  30. protected getQuery(): any {
  31. return this.ctx.request.query;
  32. }
  33. /**
  34. * 获取Body
  35. */
  36. protected getBody(): any {
  37. return this.ctx.request.body;
  38. }
  39. /**
  40. * 获取Router上的参数
  41. */
  42. protected getParams(): any {
  43. return this.ctx.params;
  44. }
  45. /**
  46. * 获取Helper
  47. */
  48. protected getHelper(): IHelper {
  49. return this.ctx.helper;
  50. }
  51. /**
  52. * 返回数据
  53. * @param op 返回配置,返回失败需要单独配置
  54. */
  55. protected res(op?: ResOp): void {
  56. this.ctx.set('Content-Type', 'application/json');
  57. this.ctx.body = {
  58. data: op?.data ?? null,
  59. code: op?.code ?? 200,
  60. message: op?.code ? this.ctx.helper.getErrorMessageByCode(`${op!.code}`) || op?.message || 'unknown error' : op?.message || 'success',
  61. };
  62. }
  63. }