
ngx-cacheable
Observable cache decorator you can use to decorate class methods which return streams and cache their return values.
Installing
To install the package, just run
npm install ngx-cacheable
Import the decorator from ngx-cacheable like:
import { Cacheable } from 'ngx-cacheable';
and use it decorate any class method like:
@Cacheable()
getUsers() {
return this.http
.get(`${environment.api}/users`);
}
Now all subsequent calls to this endpoint will be returned from an in-memory cache, rather than the actual http call!
Another example will be:
@Cacheable()
getUser(id:string) {
return this.http
.get(`${environment.api}/users/${id}`);
}
If we call this method by service.getUser(1)
, its return value will be cached and returned, up until the method is called with a different parameter. Then the old cache will be busted and a new one will take its place.
For more information and other configurations, see the configuration options below
Examples
Cache Busting
You can achieve it by decorating the cache busting method with the CacheBuster decorator. So you can have one method for fetching and caching data and another, to remove the cache. This is useful when for example you want to add an item to a list and refresh that list afterwards.
const cacheBuster$ = new Subject<void>();
export class Service {
@Cacheable({
cacheBusterObserver: cacheBuster$
})
getData() {
}
@CacheBuster({
cacheBusterNotifier: cacheBuster$
})
saveData() {
}
}
If you want to globally bust your whole cache (i.e caches of all Cacheable decorators), just import the globalCacheBusterNotifier
and call next()
on it, like:
import { globalCacheBusterNotifier } from './cacheable.decorator';
globalCacheBusterNotifier.next();
Configuration
export interface ICacheConfig {
cacheBusterObserver?: Observable<void>;
cacheResolver?: ICacheRequestResolver;
shouldCacheDecider?: IShouldCacheDecider;
maxAge?: number;
slidingExpiration?: boolean;
maxCacheCount?: number;
async?: boolean;
}
Running the tests
Just run npm test
.
Contributing
The project is open for contributors! Please file an issue or make a PR:)
Authors