-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
78 lines (70 loc) · 2.26 KB
/
main.ts
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
77
78
const Redis = require('redis');
/**
* Interfaces and local definitions
*/
export interface CacheObject
{
[key: string]: any;
}
type PromiseArrayCallback = (res: Array < CacheObject > ) => void;
type PromiseErrCallback = (err: Error) => void;
export class Cache
{
private Redis = Redis;
private _cache: any;
private dbQueryDelay: number = 1000;
constructor(cacheHost: string, cachePort: string, dbQueryDelay: number = 1000)
{
this.dbQueryDelay = dbQueryDelay;
this.closeAndConnectCache(cacheHost, cachePort);
}
/* Public methods */
public findObj(modelName: string, key ? : string, value ? : any): Promise < CacheObject | undefined >
{
return this.findObjs(modelName, key, value).then((res) =>
{
if (res && res.length > 0) return res[0];
});
}
public findObjs(modelName: string, key ? : string, value ? : any, retry ? : number): Promise < Array < CacheObject >>
{
return new Promise((resolve: PromiseArrayCallback, reject: PromiseErrCallback) =>
{
this._cache.get(modelName, (err: Error, res: string) =>
{
if (err) setTimeout(() =>
{
reject(err);
}, this.dbQueryDelay);
else resolve(res ? JSON.parse(res) : []);
});
}).then((res) =>
{
if (res.length < 1) return res;
if (!key || !value) return res;
return res.filter(obj =>
{
return obj[key] === value;
});
}).catch((err: Error) =>
{
console.error('Cache got error: ' + modelName + ' ' + JSON.stringify(err));
if (retry && retry >= 10) throw err;
else return this.findObjs(modelName, key, value, retry ? ++retry : 1);
});
}
private closeAndConnectCache(host: string, port: string): void
{
if (this._cache) this._cache.quit();
this._cache = this.Redis.createClient(
{
host: host,
port: port
});
this._cache.on('error', (err: Error) =>
{
console.error('Cache got error main: ' + JSON.stringify(err));
this.closeAndConnectCache(host, port);
});
}
}