dataRecord.service.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { Provide, Scope, ScopeEnum } from '@midwayjs/decorator';
  2. import { InjectEntityModel } from '@midwayjs/typegoose';
  3. import { ReturnModelType } from '@typegoose/typegoose';
  4. import { BaseService } from 'free-midway-component';
  5. import { DataRecord } from '../../entityRecord/dataRecord.entity';
  6. import { get } from 'lodash';
  7. import dayjs = require('dayjs');
  8. type modelType = ReturnModelType<typeof DataRecord>;
  9. @Provide()
  10. @Scope(ScopeEnum.Request, { allowDowngrade: true })
  11. export class DataRecordService extends BaseService<modelType> {
  12. @InjectEntityModel(DataRecord)
  13. model: modelType;
  14. async makeLogs(controllerName: string, methodName: string) {
  15. const req = this.ctx.request;
  16. const user = this.ctx.user;
  17. const data = {
  18. operator: user,
  19. ip: get(req, 'header.x-forwarded-for', req.ip),
  20. device: get(req, 'header.user-agent'),
  21. time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  22. controller: controllerName,
  23. method: methodName,
  24. router: get(req, 'header.referer'),
  25. };
  26. return data;
  27. }
  28. /**
  29. * 为默认函数提供原数据
  30. * defaultMethod: create, update, delete
  31. * @param service 中间件提供的controller的默认service
  32. * @param method 当前执行函数名
  33. * @returns {object} 原数据
  34. */
  35. async getDefaultMethodOriginData(service: any, method: string) {
  36. let data = null;
  37. if (method === 'create') return data;
  38. const id = get(this.ctx.request, 'params.id');
  39. const modelName = get(service, 'model.modelName');
  40. data = await service.fetch(id);
  41. return { [modelName]: [data] };
  42. }
  43. /**
  44. * 为默认函数提供新数据
  45. * defaultMethod: create, update, delete
  46. * @param service 中间件提供的controller的默认service
  47. * @param method 当前执行函数名
  48. * @param origin_data 原数据
  49. * @returns {object} 新数据
  50. */
  51. async getDefaultMethodNewData(service: any, method: string, origin_data: object) {
  52. let data = null;
  53. if (method === 'delete') return data;
  54. const modelName = get(service, 'model.modelName');
  55. if (method === 'update' || method === 'status') {
  56. if (origin_data) {
  57. const list = get(origin_data, modelName);
  58. const arr = [];
  59. for (const i of list) {
  60. const d = await service.fetch(i._id);
  61. arr.push(d);
  62. }
  63. data = arr;
  64. }
  65. } else if (method === 'create') {
  66. data = [origin_data];
  67. }
  68. return { [modelName]: data };
  69. }
  70. }