cache.js
1.27 KB
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
/*
* @Author: limin
* @Date: 2019-11-21 14:32:51
* @Last Modified by: limin
* @Last Modified time: 2019-12-05 17:34:43
*/
"use strict";
const Service = require("egg").Service;
class CacheService extends Service {
constructor(ctx) {
super(ctx);
this.session = ctx.session;
this.ResponseCode = ctx.response.ResponseCode;
this.ServerResponse = ctx.response.ServerResponse;
this.helper = ctx.helper;
this.PREFIX = ctx.helper.constant.PREFIX;
}
async set(key, value, ex = this.app.config.sys.user_cache_expires_time) {
this.app.redis && (await this.app.redis.set(`${this.PREFIX}${key}`, this.helper.json_stringify(value), "EX", ex));
}
async get(key, fnGetFromDB, ex) {
if (this.app.redis) {
var value = await this.app.redis.get(`${this.helper.constant.PREFIX}${key}`);
if(value){
value =this.helper.json_parser(value)
return value
}
}
if (fnGetFromDB) {
var data = await fnGetFromDB();
if( data && data.length ){
const{ date } =data[0]
const { today } = await this.get(this.helper.constant.DATES)
if(date.split(' ')[0] === today) {
await this.set(key, data, ex);
}
}
return data;
}
return null;
}
}
module.exports = CacheService;