a4-observable-cache
v8.1.3
Published
Observable Cache
Downloads
4
Readme
A4ObservableCache
a4-observable-cache is an angular caching service for observable. A typical use case is caching HttpClient get for front-end optimization. HttpClient methods return observable and the app will be able to cache the observable based on the arguments and evict the cache when necessary. For example, the app can cache the get method and evict the cache when an update has been done to the same data object.
Install
npm i a4-observable-cache
Example
The API service
@Cache()
getBook(isbn: string) {
return this.http.get<BookSummary>(`/api/books/${isbn}/summary`);
}
@Uncache({group: 'getBook', key: (isbn: string) => isbn})
updateBook(isbn: string, summary: string) {
return this.http.put(`/api/books/${isbn}/summary`, {summary});
}
How does it work?
Cache
this.api.getBook(this.isbn).subscribe(bookSummary => console.log(bookSummary));
Calling this repeatedly will produce the same result but the Http Get will only be invoked once. The group of the cache defaults to the method name ie getBook. You may specify a group name by @cache({group: 'book'})
. The key defaults to the arguments (as string). In this example the group is getBook and the key is the content of ISBN. Group and the key form a composite key as the hashing key for the cache.
Uncache
@Uncache({group: 'getBook', key: (isbn: string) => isbn})
updateBook(isbn: string, summary: string) {
return this.http.put(`/api/books/${isbn}/summary`, {summary});
}
Uncache will evict the cache based on the composite key specified by the group and the key. The group is a required field and the key is optional. If there is no key function provided, the arguments to the function will be used to generate the key. In this case, isbn and summary will be used as the key. This will result in no cache being evicted as the composite key used by the cache is getBook (group) and isbn (key). Thus, we need to specify how to generate the key by specifying that we want to use isbn
as part of the composite key but not summary
. If key resolves to null or an empty string, it will evict the whole group instead. eg.
@Uncache({group: 'getBook', key: () => null})
updateBookSummary(isbn: string, summary: string) {
return this.http.put(`/api/books/${isbn}/summary`, {summary});
}
@Uncache({group: 'getBook})
deleteBook(isbn: string) {
return this.http.delete(`/api/books/${isbn}`);
}
Hook Into The Cache System
const original = window['__A4_OBSERVABLE_CACHE_HOOK__'];
window['__A4_OBSERVABLE_CACHE_HOOK__'] = (eventType: EventType, key: string, cache: CacheStorage) => {
console.log(`event: ${eventType} key: ${key}`, Array.from(cache.keys()));
if (original)
original(eventType, key, cache);
};
Service
Injecting the Service
constructor(private cache: ObservableCacheService) { }
Service Interface
init(options: Options<string, unknown>);
set<T>(key: string, value: T);
get<T>(key: string): T;
uncache(group: string, key?: string);
clear();