Skip to content

Instantly share code, notes, and snippets.

@szul szul/node-cache.ts
Created Jan 27, 2020

Embed
What would you like to do?
Abstraction layer for the node-cache Node.JS package
import * as NodeCache from 'node-cache';
export class Cache {
private _cache: NodeCache;
constructor(ttlSeconds: number) {
this._cache = new NodeCache({
stdTTL: ttlSeconds,
checkperiod: (ttlSeconds * 0.2)
});
}
public getSync(key: string): any {
return this._cache.get(key);
}
public async get(key: string, callback?: Function): Promise<any> {
const value: any = this._cache.get(key);
if (value != null) {
return Promise.resolve(value);
}
try {
if(callback != null) {
const result: any = await callback();
this._cache.set(key, result);
return Promise.resolve(result);
}
return Promise.resolve(null);
}
catch(e) {
Promise.reject(e);
}
}
public set(key: string, value: any): void {
this._cache.set(key, value);
}
public del(key: string): number {
return this._cache.del(key);
}
public flush(): void {
this._cache.flushAll();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.