anote-server-libs 0.11.2 → 0.11.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.vscode/settings.json +2 -2
- package/models/ApiCall.ts +40 -40
- package/models/Migration.ts +43 -43
- package/models/repository/BaseModelRepository.js +8 -4
- package/models/repository/BaseModelRepository.ts +4 -4
- package/models/repository/CryptModelDao.js +82 -0
- package/models/repository/MemoryCache.ts +87 -87
- package/models/repository/ModelDao.ts +268 -268
- package/package.json +35 -35
- package/services/WithBody.ts +65 -65
- package/services/WithTransaction.ts +161 -161
- package/services/utils.js +24 -24
- package/services/utils.ts +269 -269
- package/tsconfig.json +29 -29
package/.vscode/settings.json
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
{
|
|
2
|
-
"
|
|
1
|
+
{
|
|
2
|
+
"js/ts.tsdk.path": "node_modules/typescript/lib"
|
|
3
3
|
}
|
package/models/ApiCall.ts
CHANGED
|
@@ -1,40 +1,40 @@
|
|
|
1
|
-
import { ConnectionPool, DateTimeOffset, Request } from 'mssql';
|
|
2
|
-
import {Pool} from 'pg';
|
|
3
|
-
import {Logger} from 'winston';
|
|
4
|
-
import {Model, ModelDao} from './repository/ModelDao';
|
|
5
|
-
|
|
6
|
-
export interface ApiCall extends Model<string> {
|
|
7
|
-
responseCode: number;
|
|
8
|
-
responseJson: string;
|
|
9
|
-
expiresAt: Date;
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
export class ApiCallRepository extends ModelDao<string, ApiCall> {
|
|
13
|
-
constructor(protected pool: Pool, protected poolMssql: ConnectionPool, protected logger: Logger) {
|
|
14
|
-
super(pool, poolMssql, logger, 'api_call', 5, pool ? 'id=$1,"updatedOn"=$2,"responseCode"=$3,"responseJson"=$4,"expiresAt"=$5' :
|
|
15
|
-
'id=@1,"updatedOn"=@2,"responseCode"=@3,"responseJson"=@4,"expiresAt"=@5');
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
buildObject(q: any): ApiCall {
|
|
19
|
-
if(!q) return undefined;
|
|
20
|
-
q.id = q.id.trim();
|
|
21
|
-
q.updatedOn = q.updatedOn && new Date(q.updatedOn);
|
|
22
|
-
q.responseCode = parseInt(q.responseCode, 10);
|
|
23
|
-
q.expiresAt = q.expiresAt && new Date(q.expiresAt);
|
|
24
|
-
return q;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
serialize(instance: ApiCall, request?: Request) {
|
|
28
|
-
if(request) {
|
|
29
|
-
request.input('1', instance.id);
|
|
30
|
-
request.input('2', DateTimeOffset, instance.updatedOn);
|
|
31
|
-
request.input('3', instance.responseCode);
|
|
32
|
-
request.input('4', instance.responseJson);
|
|
33
|
-
request.input('5', DateTimeOffset, instance.expiresAt);
|
|
34
|
-
return undefined;
|
|
35
|
-
} else {
|
|
36
|
-
return [instance.id, instance.updatedOn, instance.responseCode, instance.responseJson, instance.expiresAt];
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
}
|
|
1
|
+
import { ConnectionPool, DateTimeOffset, Request } from 'mssql';
|
|
2
|
+
import {Pool} from 'pg';
|
|
3
|
+
import {Logger} from 'winston';
|
|
4
|
+
import {Model, ModelDao} from './repository/ModelDao';
|
|
5
|
+
|
|
6
|
+
export interface ApiCall extends Model<string> {
|
|
7
|
+
responseCode: number;
|
|
8
|
+
responseJson: string;
|
|
9
|
+
expiresAt: Date;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export class ApiCallRepository extends ModelDao<string, ApiCall> {
|
|
13
|
+
constructor(protected pool: Pool, protected poolMssql: ConnectionPool, protected logger: Logger) {
|
|
14
|
+
super(pool, poolMssql, logger, 'api_call', 5, pool ? 'id=$1,"updatedOn"=$2,"responseCode"=$3,"responseJson"=$4,"expiresAt"=$5' :
|
|
15
|
+
'id=@1,"updatedOn"=@2,"responseCode"=@3,"responseJson"=@4,"expiresAt"=@5');
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
buildObject(q: any): ApiCall {
|
|
19
|
+
if(!q) return undefined;
|
|
20
|
+
q.id = q.id.trim();
|
|
21
|
+
q.updatedOn = q.updatedOn && new Date(q.updatedOn);
|
|
22
|
+
q.responseCode = parseInt(q.responseCode, 10);
|
|
23
|
+
q.expiresAt = q.expiresAt && new Date(q.expiresAt);
|
|
24
|
+
return q;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
serialize(instance: ApiCall, request?: Request) {
|
|
28
|
+
if(request) {
|
|
29
|
+
request.input('1', instance.id);
|
|
30
|
+
request.input('2', DateTimeOffset, instance.updatedOn);
|
|
31
|
+
request.input('3', instance.responseCode);
|
|
32
|
+
request.input('4', instance.responseJson);
|
|
33
|
+
request.input('5', DateTimeOffset, instance.expiresAt);
|
|
34
|
+
return undefined;
|
|
35
|
+
} else {
|
|
36
|
+
return [instance.id, instance.updatedOn, instance.responseCode, instance.responseJson, instance.expiresAt];
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
}
|
package/models/Migration.ts
CHANGED
|
@@ -1,43 +1,43 @@
|
|
|
1
|
-
import { ConnectionPool, Request } from 'mssql';
|
|
2
|
-
import {Pool} from 'pg';
|
|
3
|
-
import {Logger} from 'winston';
|
|
4
|
-
import {ModelDao} from './repository/ModelDao';
|
|
5
|
-
|
|
6
|
-
export interface Migration {
|
|
7
|
-
id: number;
|
|
8
|
-
hash: string;
|
|
9
|
-
sqlUp: string;
|
|
10
|
-
sqlDown: string;
|
|
11
|
-
state: number;
|
|
12
|
-
skip: boolean;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
export class MigrationRepository extends ModelDao<number, Migration> {
|
|
16
|
-
constructor(protected pool: Pool, protected poolMssql: ConnectionPool, protected logger: Logger) {
|
|
17
|
-
super(pool, poolMssql, logger, 'migration', 6, pool ? 'id=$1,hash=$2,"sqlUp"=$3,"sqlDown"=$4,state=$5,skip=$6' :
|
|
18
|
-
'id=@1,hash=@2,"sqlUp"=@3,"sqlDown"=@4,state=@5,skip=@6');
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
buildObject(q: any): Migration {
|
|
22
|
-
if(!q) return undefined;
|
|
23
|
-
q.id = parseInt(q.id, 10);
|
|
24
|
-
q.hash = q.hash.trim();
|
|
25
|
-
q.state = parseInt(q.state, 10);
|
|
26
|
-
q.skip = q.skip ? true : false;
|
|
27
|
-
return q;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
serialize(instance: Migration, request?: Request) {
|
|
31
|
-
if(request) {
|
|
32
|
-
request.input('1', instance.id);
|
|
33
|
-
request.input('2', instance.hash);
|
|
34
|
-
request.input('3', instance.sqlUp);
|
|
35
|
-
request.input('4', instance.sqlDown);
|
|
36
|
-
request.input('5', instance.state);
|
|
37
|
-
request.input('6', instance.skip ? 1 : 0);
|
|
38
|
-
return undefined;
|
|
39
|
-
} else {
|
|
40
|
-
return [instance.id, instance.hash, instance.sqlUp, instance.sqlDown, instance.state, instance.skip];
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
}
|
|
1
|
+
import { ConnectionPool, Request } from 'mssql';
|
|
2
|
+
import {Pool} from 'pg';
|
|
3
|
+
import {Logger} from 'winston';
|
|
4
|
+
import {ModelDao} from './repository/ModelDao';
|
|
5
|
+
|
|
6
|
+
export interface Migration {
|
|
7
|
+
id: number;
|
|
8
|
+
hash: string;
|
|
9
|
+
sqlUp: string;
|
|
10
|
+
sqlDown: string;
|
|
11
|
+
state: number;
|
|
12
|
+
skip: boolean;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export class MigrationRepository extends ModelDao<number, Migration> {
|
|
16
|
+
constructor(protected pool: Pool, protected poolMssql: ConnectionPool, protected logger: Logger) {
|
|
17
|
+
super(pool, poolMssql, logger, 'migration', 6, pool ? 'id=$1,hash=$2,"sqlUp"=$3,"sqlDown"=$4,state=$5,skip=$6' :
|
|
18
|
+
'id=@1,hash=@2,"sqlUp"=@3,"sqlDown"=@4,state=@5,skip=@6');
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
buildObject(q: any): Migration {
|
|
22
|
+
if(!q) return undefined;
|
|
23
|
+
q.id = parseInt(q.id, 10);
|
|
24
|
+
q.hash = q.hash.trim();
|
|
25
|
+
q.state = parseInt(q.state, 10);
|
|
26
|
+
q.skip = q.skip ? true : false;
|
|
27
|
+
return q;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
serialize(instance: Migration, request?: Request) {
|
|
31
|
+
if(request) {
|
|
32
|
+
request.input('1', instance.id);
|
|
33
|
+
request.input('2', instance.hash);
|
|
34
|
+
request.input('3', instance.sqlUp);
|
|
35
|
+
request.input('4', instance.sqlDown);
|
|
36
|
+
request.input('5', instance.state);
|
|
37
|
+
request.input('6', instance.skip ? 1 : 0);
|
|
38
|
+
return undefined;
|
|
39
|
+
} else {
|
|
40
|
+
return [instance.id, instance.hash, instance.sqlUp, instance.sqlDown, instance.state, instance.skip];
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -57,7 +57,7 @@ END`)
|
|
|
57
57
|
if (migrations.find(migration => migration.state !== 0))
|
|
58
58
|
process.exit(4);
|
|
59
59
|
fs.readdir(migrationsPath, (_, files) => {
|
|
60
|
-
|
|
60
|
+
let migrationsAvailable = files
|
|
61
61
|
.filter(file => /[0-9]+\.sql/.test(file))
|
|
62
62
|
.map(file => parseInt(file.split('.sql')[0], 10))
|
|
63
63
|
.filter(file => file > 0)
|
|
@@ -73,15 +73,19 @@ END`)
|
|
|
73
73
|
const minAvailableId = migrationsAvailable.length > 0 ? migrationsAvailable[0].id : 0;
|
|
74
74
|
const maxAvailableId = migrationsAvailable.length > 0 ? migrationsAvailable[migrationsAvailable.length - 1].id : Infinity;
|
|
75
75
|
migrations = migrations.filter(m => m.id >= minAvailableId && m.id <= maxAvailableId);
|
|
76
|
-
if (onlyAboveOrEquals)
|
|
76
|
+
if (onlyAboveOrEquals) {
|
|
77
77
|
migrations = migrations.filter(m => m.id >= onlyAboveOrEquals);
|
|
78
|
-
|
|
78
|
+
migrationsAvailable = migrationsAvailable.filter(m => m.id >= onlyAboveOrEquals);
|
|
79
|
+
}
|
|
80
|
+
if (onlyBelow) {
|
|
79
81
|
migrations = migrations.filter(m => m.id < onlyBelow);
|
|
82
|
+
migrationsAvailable = migrationsAvailable.filter(m => m.id < onlyBelow);
|
|
83
|
+
}
|
|
80
84
|
if (migrationsAvailable.length === 0 && migrations.length === 0)
|
|
81
85
|
process.exit(5);
|
|
82
86
|
if (migrationsAvailable.length && migrationsAvailable.length !== (migrationsAvailable[migrationsAvailable.length - 1].id - migrationsAvailable[0].id + 1))
|
|
83
87
|
process.exit(5);
|
|
84
|
-
let highestCommon =
|
|
88
|
+
let highestCommon = 0;
|
|
85
89
|
while (highestCommon < migrations.length && highestCommon < migrationsAvailable.length
|
|
86
90
|
&& migrations[highestCommon].hash === migrationsAvailable[highestCommon].hash)
|
|
87
91
|
highestCommon++;
|
|
@@ -58,7 +58,7 @@ END`)])).then(() => {
|
|
|
58
58
|
if(migrations.find(migration => migration.state !== 0)) process.exit(4); // Have to fix manually
|
|
59
59
|
// Read the new ones
|
|
60
60
|
fs.readdir(migrationsPath, (_, files) => {
|
|
61
|
-
|
|
61
|
+
let migrationsAvailable = files
|
|
62
62
|
.filter(file => /[0-9]+\.sql/.test(file))
|
|
63
63
|
.map(file => parseInt(file.split('.sql')[0], 10))
|
|
64
64
|
.filter(file => file > 0)
|
|
@@ -74,11 +74,11 @@ END`)])).then(() => {
|
|
|
74
74
|
const minAvailableId = migrationsAvailable.length > 0 ? migrationsAvailable[0].id : 0;
|
|
75
75
|
const maxAvailableId = migrationsAvailable.length > 0 ? migrationsAvailable[migrationsAvailable.length - 1].id : Infinity;
|
|
76
76
|
migrations = migrations.filter(m => m.id >= minAvailableId && m.id <= maxAvailableId);
|
|
77
|
-
if(onlyAboveOrEquals) migrations = migrations.filter(m => m.id >= onlyAboveOrEquals);
|
|
78
|
-
if(onlyBelow) migrations = migrations.filter(m => m.id < onlyBelow);
|
|
77
|
+
if(onlyAboveOrEquals) { migrations = migrations.filter(m => m.id >= onlyAboveOrEquals); migrationsAvailable = migrationsAvailable.filter(m => m.id >= onlyAboveOrEquals); }
|
|
78
|
+
if(onlyBelow) { migrations = migrations.filter(m => m.id < onlyBelow); migrationsAvailable = migrationsAvailable.filter(m => m.id < onlyBelow); }
|
|
79
79
|
if(migrationsAvailable.length === 0 && migrations.length === 0) process.exit(5);
|
|
80
80
|
if(migrationsAvailable.length && migrationsAvailable.length !== (migrationsAvailable[migrationsAvailable.length - 1].id - migrationsAvailable[0].id + 1)) process.exit(5);
|
|
81
|
-
let highestCommon =
|
|
81
|
+
let highestCommon = 0;
|
|
82
82
|
while(highestCommon < migrations.length && highestCommon < migrationsAvailable.length
|
|
83
83
|
&& migrations[highestCommon].hash === migrationsAvailable[highestCommon].hash)
|
|
84
84
|
highestCommon++;
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.CryptModelDao = void 0;
|
|
4
|
+
const crypto_1 = require("crypto");
|
|
5
|
+
const util_1 = require("util");
|
|
6
|
+
const ModelDao_1 = require("./ModelDao");
|
|
7
|
+
const randomFillAsync = (0, util_1.promisify)(crypto_1.randomFill);
|
|
8
|
+
class CryptModelDao extends ModelDao_1.ModelDao {
|
|
9
|
+
constructor(keyBase64, encryptedColumns, ...args) {
|
|
10
|
+
super(...args);
|
|
11
|
+
this.key = Buffer.from(keyBase64, 'base64');
|
|
12
|
+
this.encryptedColumns = encryptedColumns;
|
|
13
|
+
}
|
|
14
|
+
serializeWrapper(instance, request) {
|
|
15
|
+
const props = this.serialize(instance, request);
|
|
16
|
+
const encryptPromises = [];
|
|
17
|
+
this.encryptedColumns.forEach(col => {
|
|
18
|
+
const idx = this.updateDefinition.split(',').findIndex(def => def.trim().startsWith('"' + col + '"') || def.trim().startsWith(col + '='));
|
|
19
|
+
if (idx >= 0) {
|
|
20
|
+
const val = request ? request.parameters[idx] : props[idx];
|
|
21
|
+
if (val !== null && val !== undefined) {
|
|
22
|
+
const encryptPromise = this.encrypt(String(val)).then(encrypted => {
|
|
23
|
+
if (request)
|
|
24
|
+
request.replaceInput(String(idx + 1), encrypted);
|
|
25
|
+
else
|
|
26
|
+
props[idx] = encrypted;
|
|
27
|
+
});
|
|
28
|
+
encryptPromises.push(encryptPromise);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
if (encryptPromises.length > 0) {
|
|
33
|
+
return Promise.all(encryptPromises).then(() => props);
|
|
34
|
+
}
|
|
35
|
+
return props;
|
|
36
|
+
}
|
|
37
|
+
buildObjectWrapper(row) {
|
|
38
|
+
const decryptPromises = [];
|
|
39
|
+
this.encryptedColumns.forEach(col => {
|
|
40
|
+
if (row[col] !== null && row[col] !== undefined) {
|
|
41
|
+
const decryptPromise = this.decrypt(String(row[col])).then(decrypted => {
|
|
42
|
+
row[col] = decrypted;
|
|
43
|
+
});
|
|
44
|
+
decryptPromises.push(decryptPromise);
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
if (decryptPromises.length > 0) {
|
|
48
|
+
return Promise.all(decryptPromises).then(() => this.buildObject(row));
|
|
49
|
+
}
|
|
50
|
+
return this.buildObject(row);
|
|
51
|
+
}
|
|
52
|
+
async encrypt(decrypted) {
|
|
53
|
+
const iv = new Uint8Array(16);
|
|
54
|
+
await randomFillAsync(iv);
|
|
55
|
+
const cipher = (0, crypto_1.createCipheriv)(CryptModelDao.ALGORITHM, this.key, iv);
|
|
56
|
+
let encrypted = '';
|
|
57
|
+
cipher.setEncoding('base64');
|
|
58
|
+
cipher.on('data', (chunk) => encrypted += chunk);
|
|
59
|
+
cipher.write(decrypted);
|
|
60
|
+
cipher.end();
|
|
61
|
+
return `$$enc$$:${Buffer.from(iv).toString('base64')}${encrypted}`;
|
|
62
|
+
}
|
|
63
|
+
async decrypt(encrypted) {
|
|
64
|
+
if (!encrypted.startsWith('$$enc$$:')) {
|
|
65
|
+
return encrypted;
|
|
66
|
+
}
|
|
67
|
+
encrypted = encrypted.slice(8);
|
|
68
|
+
const iv = new Uint8Array(Buffer.from(encrypted.slice(0, 24), 'base64'));
|
|
69
|
+
const decipher = (0, crypto_1.createDecipheriv)(CryptModelDao.ALGORITHM, this.key, iv);
|
|
70
|
+
let decrypted = '';
|
|
71
|
+
decipher.on('readable', () => {
|
|
72
|
+
for (let chunk = decipher.read(); chunk !== null; chunk = decipher.read()) {
|
|
73
|
+
decrypted += chunk.toString('base64');
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
decipher.write(encrypted.slice(24), 'base64');
|
|
77
|
+
decipher.end();
|
|
78
|
+
return Buffer.from(decrypted, 'base64').toString('utf8');
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
exports.CryptModelDao = CryptModelDao;
|
|
82
|
+
CryptModelDao.ALGORITHM = 'aes-256-cbc';
|
|
@@ -1,87 +1,87 @@
|
|
|
1
|
-
import * as Memcached from 'memcached';
|
|
2
|
-
|
|
3
|
-
export class MemoryCache<T> {
|
|
4
|
-
|
|
5
|
-
private localCache: {[id: string]: any} = {};
|
|
6
|
-
|
|
7
|
-
constructor(private localKey: string, private cache?: Memcached) {
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
list(): Promise<T[]> {
|
|
11
|
-
if(this.cache) return new Promise(resolve => {
|
|
12
|
-
let pending = true;
|
|
13
|
-
setTimeout(() => {
|
|
14
|
-
if(pending) {
|
|
15
|
-
pending = false;
|
|
16
|
-
resolve([]);
|
|
17
|
-
}
|
|
18
|
-
}, 250);
|
|
19
|
-
this.cache.items((_, data) => {
|
|
20
|
-
if(pending) {
|
|
21
|
-
pending = false;
|
|
22
|
-
resolve(data.map(s => {
|
|
23
|
-
const value = <string>s[Object.getOwnPropertyNames(s).find(sname => sname.startsWith(this.localKey))];
|
|
24
|
-
return value && JSON.parse(value);
|
|
25
|
-
}).filter(x => x));
|
|
26
|
-
}
|
|
27
|
-
});
|
|
28
|
-
});
|
|
29
|
-
else return Promise.resolve(Object.getOwnPropertyNames(this.localCache).map(key => this.localCache[key]));
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
get(key: string | number): Promise<T> {
|
|
33
|
-
if(this.cache) return new Promise(resolve => {
|
|
34
|
-
let pending = true;
|
|
35
|
-
setTimeout(() => {
|
|
36
|
-
if(pending) {
|
|
37
|
-
pending = false;
|
|
38
|
-
resolve(undefined);
|
|
39
|
-
}
|
|
40
|
-
}, 250);
|
|
41
|
-
this.cache.get(this.localKey + key, (_, data) => {
|
|
42
|
-
if(pending) {
|
|
43
|
-
pending = false;
|
|
44
|
-
resolve(data && JSON.parse(data));
|
|
45
|
-
}
|
|
46
|
-
});
|
|
47
|
-
});
|
|
48
|
-
else return Promise.resolve(this.localCache[key]);
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
set(key: string | number, val: T, time = 15 * 60): Promise<void> {
|
|
52
|
-
if(this.cache) return new Promise(resolve => this.cache.set(this.localKey + key, JSON.stringify(val), time, resolve));
|
|
53
|
-
else {
|
|
54
|
-
this.localCache[key] = val;
|
|
55
|
-
return Promise.resolve();
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
delete(key: string | number): Promise<void> {
|
|
60
|
-
if(this.cache) {
|
|
61
|
-
return new Promise(resolve => {
|
|
62
|
-
let fired = false;
|
|
63
|
-
const handler = setTimeout(() => {
|
|
64
|
-
fired = true;
|
|
65
|
-
resolve();
|
|
66
|
-
}, 50);
|
|
67
|
-
this.cache.del(this.localKey + key, () => {
|
|
68
|
-
if(!fired) {
|
|
69
|
-
clearTimeout(handler);
|
|
70
|
-
resolve();
|
|
71
|
-
}
|
|
72
|
-
});
|
|
73
|
-
});
|
|
74
|
-
} else {
|
|
75
|
-
this.localCache[key] = undefined;
|
|
76
|
-
return Promise.resolve();
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
clear() {
|
|
81
|
-
if(this.cache) {
|
|
82
|
-
this.localKey = this.localKey + '_';
|
|
83
|
-
if(this.localKey.length > 40)
|
|
84
|
-
this.localKey = this.localKey.replace(/_+$/, '');
|
|
85
|
-
} else this.localCache = {};
|
|
86
|
-
}
|
|
87
|
-
}
|
|
1
|
+
import * as Memcached from 'memcached';
|
|
2
|
+
|
|
3
|
+
export class MemoryCache<T> {
|
|
4
|
+
|
|
5
|
+
private localCache: {[id: string]: any} = {};
|
|
6
|
+
|
|
7
|
+
constructor(private localKey: string, private cache?: Memcached) {
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
list(): Promise<T[]> {
|
|
11
|
+
if(this.cache) return new Promise(resolve => {
|
|
12
|
+
let pending = true;
|
|
13
|
+
setTimeout(() => {
|
|
14
|
+
if(pending) {
|
|
15
|
+
pending = false;
|
|
16
|
+
resolve([]);
|
|
17
|
+
}
|
|
18
|
+
}, 250);
|
|
19
|
+
this.cache.items((_, data) => {
|
|
20
|
+
if(pending) {
|
|
21
|
+
pending = false;
|
|
22
|
+
resolve(data.map(s => {
|
|
23
|
+
const value = <string>s[Object.getOwnPropertyNames(s).find(sname => sname.startsWith(this.localKey))];
|
|
24
|
+
return value && JSON.parse(value);
|
|
25
|
+
}).filter(x => x));
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
});
|
|
29
|
+
else return Promise.resolve(Object.getOwnPropertyNames(this.localCache).map(key => this.localCache[key]));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
get(key: string | number): Promise<T> {
|
|
33
|
+
if(this.cache) return new Promise(resolve => {
|
|
34
|
+
let pending = true;
|
|
35
|
+
setTimeout(() => {
|
|
36
|
+
if(pending) {
|
|
37
|
+
pending = false;
|
|
38
|
+
resolve(undefined);
|
|
39
|
+
}
|
|
40
|
+
}, 250);
|
|
41
|
+
this.cache.get(this.localKey + key, (_, data) => {
|
|
42
|
+
if(pending) {
|
|
43
|
+
pending = false;
|
|
44
|
+
resolve(data && JSON.parse(data));
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
else return Promise.resolve(this.localCache[key]);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
set(key: string | number, val: T, time = 15 * 60): Promise<void> {
|
|
52
|
+
if(this.cache) return new Promise(resolve => this.cache.set(this.localKey + key, JSON.stringify(val), time, resolve));
|
|
53
|
+
else {
|
|
54
|
+
this.localCache[key] = val;
|
|
55
|
+
return Promise.resolve();
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
delete(key: string | number): Promise<void> {
|
|
60
|
+
if(this.cache) {
|
|
61
|
+
return new Promise(resolve => {
|
|
62
|
+
let fired = false;
|
|
63
|
+
const handler = setTimeout(() => {
|
|
64
|
+
fired = true;
|
|
65
|
+
resolve();
|
|
66
|
+
}, 50);
|
|
67
|
+
this.cache.del(this.localKey + key, () => {
|
|
68
|
+
if(!fired) {
|
|
69
|
+
clearTimeout(handler);
|
|
70
|
+
resolve();
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
});
|
|
74
|
+
} else {
|
|
75
|
+
this.localCache[key] = undefined;
|
|
76
|
+
return Promise.resolve();
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
clear() {
|
|
81
|
+
if(this.cache) {
|
|
82
|
+
this.localKey = this.localKey + '_';
|
|
83
|
+
if(this.localKey.length > 40)
|
|
84
|
+
this.localKey = this.localKey.replace(/_+$/, '');
|
|
85
|
+
} else this.localCache = {};
|
|
86
|
+
}
|
|
87
|
+
}
|