wangrong
2022-06-28 19f5f603fb890e84e43fadcf3135e660802026d0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { Inject, Provide } from '@midwayjs/decorator';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/orm';
import { Repository } from 'typeorm';
import { Context } from 'egg';
import * as _ from 'lodash';
import { BaseSysLogEntity } from '../../entity/sys/log';
import * as moment from 'moment';
import { Utils } from '../../../../comm/utils';
import { BaseSysConfService } from './conf';
 
/**
 * 描述
 */
@Provide()
export class BaseSysLogService extends BaseService {
  @Inject()
  ctx: Context;
 
  @Inject()
  utils: Utils;
 
  @InjectEntityModel(BaseSysLogEntity)
  baseSysLogEntity: Repository<BaseSysLogEntity>;
 
  @Inject()
  baseSysConfService: BaseSysConfService;
 
  /**
   * 记录
   * @param url URL地址
   * @param params 参数
   * @param userId 用户ID
   */
  async record(context: Context, url, params, userId) {
    const ip = await this.utils.getReqIP(context);
    const sysLog = new BaseSysLogEntity();
    sysLog.userId = userId;
    sysLog.ip = typeof ip === 'string' ? ip : ip.join(',');
    const ipAddrArr = [];
    for (const e of sysLog.ip.split(','))
      ipAddrArr.push(await await this.utils.getIpAddr(context, e));
    sysLog.ipAddr = ipAddrArr.join(',');
    sysLog.action = url;
    if (!_.isEmpty(params)) {
      sysLog.params = JSON.stringify(params);
    }
    await this.baseSysLogEntity.insert(sysLog);
  }
 
  /**
   * 日志
   * @param isAll 是否清除全部
   */
  async clear(isAll?) {
    if (isAll) {
      await this.baseSysLogEntity.clear();
      return;
    }
    const keepDay = await this.baseSysConfService.getValue('logKeep');
    if (keepDay) {
      const beforeDate = `${moment()
        .add(-keepDay, 'days')
        .format('YYYY-MM-DD')} 00:00:00`;
      await this.baseSysLogEntity
        .createQueryBuilder()
        .where('createTime < :createTime', { createTime: beforeDate });
      await this.nativeQuery(
        ' delete from t_sys_log where createTime < ? ',
        [beforeDate]
      );
    } else {
      await this.baseSysLogEntity.clear();
    }
  }
}