Skip to content

Instantly share code, notes, and snippets.

@plaisted
Last active November 8, 2017 23:31
Show Gist options
  • Save plaisted/6a536cfae6ccfaf0cd78fe8cc63ba2dc to your computer and use it in GitHub Desktop.
Save plaisted/6a536cfae6ccfaf0cd78fe8cc63ba2dc to your computer and use it in GitHub Desktop.
Simple Angular Object Cache
import { Injectable } from '@angular/core';
@Injectable()
export class CacheService {
_dict: Map<string, CacheItem>;
constructor() {
this._dict = new Map<string, CacheItem>();
}
public Get(key: string): any {
if (this.Exists(key)) {
return this._dict.get(key).Item;
}
return undefined;
}
public GetOrSetValue<T>(key: string, lookup: () => Promise<T>, expMinutes: number): Promise<T> {
if (this.Exists(key)) {
return Promise.resolve(this.Get(key) as T);
}
return lookup().then(result => {
this.Set(key, result, expMinutes);
return result;
});
}
public Set(key: string, value: any, expMinutes: number) {
this._dict.set(key, { Item: value, ExpirationTime: (Date.now() + expMinutes * 60000)} as CacheItem);
}
public Exists(key: string): boolean {
if (this._dict.has(key)) {
const val = this._dict.get(key);
if (val.ExpirationTime > Date.now()) {
return true;
}
this._dict.delete(key);
}
return false;
}
public Delete(key: string): boolean {
return this._dict.delete(key);
}
public Clear() {
this._dict = new Map<string, CacheItem>();
}
public ClearCategory(category: string): number {
let count = 0;
this._dict.forEach((value: CacheItem, key: string) => {
if (key.startsWith(category + ':')) {
if (this._dict.delete(key)) {
count++;
}
}
});
return count;
}
}
class CacheItem {
public Item: any;
public ExpirationTime: number;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment