opera.service.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { Inject, MidwayWebRouterService, Provide } from '@midwayjs/core';
  2. import { InjectEntityModel } from '@midwayjs/typeorm';
  3. import { Repository } from 'typeorm';
  4. import { get } from 'lodash';
  5. import dayjs = require('dayjs');
  6. import { Context } from '@midwayjs/koa';
  7. import { TypeORMDataSourceManager } from '@midwayjs/typeorm';
  8. import { Opera } from '../../entityLogs/opera.entity';
  9. @Provide()
  10. export class OperaService {
  11. @Inject()
  12. ctx: Context;
  13. @InjectEntityModel(Opera, 'logs')
  14. model: Repository<Opera>;
  15. @Inject()
  16. webRouterService: MidwayWebRouterService;
  17. @Inject()
  18. dataSourceManager: TypeORMDataSourceManager;
  19. /**
  20. * 生成日志
  21. * 原数据和新数据格式:
  22. * {
  23. * [表名]:[数据,...数据]
  24. * }
  25. * @param origin_data 原数据
  26. * @param new_data 新数据
  27. */
  28. async toMakeLogs(origin_data?: object, new_data?: object) {
  29. const req = this.ctx.request;
  30. const user = this.ctx.user;
  31. const logInfo: any = {
  32. // 操作人
  33. operator_id: user.id,
  34. operator_name: get(user, 'nick_name', get(user, 'name')),
  35. // ip
  36. ip: get(req, 'header.x-forwarded-for', req.ip),
  37. // 设备
  38. device: get(req, 'header.user-agent'),
  39. // 操作时间
  40. time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  41. // 操作地址
  42. referer: get(req, 'header.referer'),
  43. // 请求地址uri
  44. path: get(req, 'path'),
  45. // 地址参数
  46. params: get(req, 'params'),
  47. // 请求参数
  48. query: get(req, 'query'),
  49. // 方法体参数
  50. body: get(req, 'body'),
  51. // 操作业务:可以通过路由注解的routerName来获取
  52. opera: null,
  53. // 变动值: 表:[数据] 需要自己组织
  54. origin_data: origin_data,
  55. new_data: new_data,
  56. };
  57. const routeInfo = await this.webRouterService.getMatchedRouterInfo(this.ctx.path, this.ctx.method);
  58. if (routeInfo) logInfo.opera = get(routeInfo, 'routerName');
  59. await this.model.insert(logInfo);
  60. }
  61. }