feat: setExpiring for NocoCache

This commit is contained in:
mertmit
2023-10-04 14:57:19 +00:00
parent 4341c61de1
commit 9ca585a33c
4 changed files with 66 additions and 0 deletions

View File

@@ -1,6 +1,11 @@
export default abstract class CacheMgr {
public abstract get(key: string, type: string): Promise<any>;
public abstract set(key: string, value: any): Promise<any>;
public abstract setExpiring(
key: string,
value: any,
seconds: number,
): Promise<any>;
public abstract del(key: string): Promise<any>;
public abstract getAll(pattern: string): Promise<any[]>;
public abstract delAll(scope: string, pattern: string): Promise<any[]>;

View File

@@ -29,6 +29,15 @@ export default class NocoCache {
return this.client.set(`${this.prefix}:${key}`, value);
}
public static async setExpiring(key, value, expireSeconds): Promise<boolean> {
if (this.cacheDisabled) return Promise.resolve(true);
return this.client.setExpiring(
`${this.prefix}:${key}`,
value,
expireSeconds,
);
}
public static async get(key, type): Promise<any> {
if (this.cacheDisabled) {
if (type === CacheGetType.TYPE_ARRAY) return Promise.resolve([]);

View File

@@ -94,6 +94,30 @@ export default class RedisCacheMgr extends CacheMgr {
}
}
// @ts-ignore
async setExpiring(key: string, value: any, seconds: number): Promise<any> {
if (typeof value !== 'undefined' && value) {
log(
`RedisCacheMgr::set: setting key ${key} with value ${value} for ${seconds} seconds`,
);
if (typeof value === 'object') {
if (Array.isArray(value) && value.length) {
return this.client.sadd(key, value);
}
return this.client.set(
key,
JSON.stringify(value, this.getCircularReplacer()),
'EX',
seconds,
);
}
return this.client.set(key, value, 'EX', seconds);
} else {
log(`RedisCacheMgr::set: value is empty for ${key}. Skipping ...`);
return Promise.resolve(true);
}
}
// @ts-ignore
async getAll(pattern: string): Promise<any> {
return this.client.hgetall(pattern);

View File

@@ -89,6 +89,34 @@ export default class RedisMockCacheMgr extends CacheMgr {
}
}
// @ts-ignore
async setExpiring(key: string, value: any, seconds: number): Promise<any> {
if (typeof value !== 'undefined' && value) {
log(
`RedisMockCacheMgr::set: setting key ${key} with value ${value} for ${seconds} seconds`,
);
// TODO: better way to handle expiration in mock redis
setTimeout(() => {
this.del(key);
}, seconds * 1000);
if (typeof value === 'object') {
if (Array.isArray(value) && value.length) {
return this.client.sadd(key, value);
}
return this.client.set(
key,
JSON.stringify(value, this.getCircularReplacer()),
);
}
return this.client.set(key, value);
} else {
log(`RedisMockCacheMgr::set: value is empty for ${key}. Skipping ...`);
return Promise.resolve(true);
}
}
// @ts-ignore
async getAll(pattern: string): Promise<any> {
return this.client.hgetall(pattern);