Skip to content

Instantly share code, notes, and snippets.

@chetbis
Last active May 2, 2020 12:26
Show Gist options
  • Save chetbis/f682f30c886859fba5df9c519e4aa478 to your computer and use it in GitHub Desktop.
Save chetbis/f682f30c886859fba5df9c519e4aa478 to your computer and use it in GitHub Desktop.
A simple key value cache
import {interval, Subscription} from 'rxjs';
import {take} from 'rxjs/operators';
import * as cloneDeep from 'lodash.clonedeep';
import {Injectable} from '@angular/core';
export interface IStoreValue {
_timeout?: Subscription;
[key: string]: any;
}
@Injectable({providedIn: 'root'})
export class SimpleCacheService {
private readonly cache = new Map<string, IStoreValue>();
/**
* Insert or overwrite data
* @param key key associated with the value
* @param value value to store
* @param ttl Time to live in milliseconds
*/
set(key: string, value: IStoreValue, ttl?: number) {
value = cloneDeep(value);
// if value already exists clear the timeout
if (this.has(key)) {
this.remove(key);
}
if (ttl) {
// delete the value from the cache after timer times out
value._timeout = interval(ttl)
.pipe(take(1))
.subscribe(this.remove.bind(this, key));
}
this.cache.set(key, value);
}
get(key: string): IStoreValue {
return this.cache.get(key);
}
has(key: string) {
return this.cache.has(key);
}
/**
* Delete cached data
* @param key item to remove
*/
remove(key: string) {
if (this.has(key)) {
const cachedItem = this.get(key);
cachedItem?._timeout.unsubscribe();
cachedItem._timeout = null;
return this.cache.delete(key);
}
return false;
}
/**
* Removes all items from the cache
*/
removeAll() {
this.cache.forEach((value, key) => {
this.remove(key);
});
}
/**
* Returns the cache size
*/
size() {
return this.cache.size;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment