wangrong
2022-03-16 a45591fc22c088fe45fafb651b0c4575cc5c2f0f
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
import { Inject, Provide } from '@midwayjs/decorator';
import { BaseService, ICoolCache } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/orm';
import { Repository } from 'typeorm';
import { BaseSysParamEntity } from '../../entity/sys/param';
 
/**
 * 参数配置
 */
@Provide()
export class BaseSysParamService extends BaseService {
  @InjectEntityModel(BaseSysParamEntity)
  baseSysParamEntity: Repository<BaseSysParamEntity>;
 
  @Inject('cool:cache')
  coolCache: ICoolCache;
 
  /**
   * 根据key获得对应的参数
   * @param key
   */
  async dataByKey(key) {
    let result = await this.coolCache.get(`param:${key}`);
    if (result) {
      result = JSON.parse(result);
      if (result.dataType !== 0) {
        return JSON.parse(result.data);
      } else {
        return result.data;
      }
    }
    return;
  }
 
  /**
   * 根据key获得对应的网页数据
   * @param key
   */
  async htmlByKey(key) {
    let html = '<html><body>@content</body></html>';
    let result = await this.coolCache.get(`param:${key}`);
    if (result) {
      result = JSON.parse(result);
      html = html.replace('@content', result.data);
    } else {
      html = html.replace('@content', 'key notfound');
    }
    return html;
  }
 
  /**
   * 重新初始化缓存
   */
  async modifyAfter() {
    const params = await this.baseSysParamEntity.find();
    for (const param of params) {
      await this.coolCache.set(`param:${param.keyName}`, JSON.stringify(param));
    }
  }
}