Skip to content

Instantly share code, notes, and snippets.

@bsamartins
Last active December 8, 2022 09:29
Show Gist options
  • Save bsamartins/a1a83e28723b86914799778797752811 to your computer and use it in GitHub Desktop.
Save bsamartins/a1a83e28723b86914799778797752811 to your computer and use it in GitHub Desktop.
Angular Universal Caching Service
@Injectable()
export class HttpCacheService {
constructor(public _http: Http,
public _cache: CacheService,
@Inject("isNode") public isNode:boolean,
@Inject("isBrowser") public isBrowser:boolean) { }
get<T>(url, options?: RequestOptionsArgs, autoClear: boolean = true, browserCaching:boolean = false): Observable<T> {
// You want to return the cache if there is a response in it.
// This would cache the first response so if your API isn't idempotent you probably want to
// remove the item from the cache after you use it. LRU of 1
let key = this.createKey(url, options);
if (this._cache.has(key)) {
const cachedResponse = this._cache.get(key);
// if autoClear is set to false, item will stay in cache until you manually clear it
// ie: trigger CacheService.remove(url /* with the url/key used here */)
if (autoClear) {
// remove previous value automatically for now
this._cache.remove(key);
}
return Observable.of(cachedResponse);
}
// note: you probably shouldn't .share() and you should write the correct logic
return this._http.get(url, options)
.map(res => res.json())
.do(json => {
if(this.isNode || (this.isBrowser && browserCaching)) {
this._cache.set(key, json)
}
})
.share();
}
createKey(url:string, options?: RequestOptionsArgs):string {
let key = url;
if(options && options.search) {
let search:string;
if(options.search instanceof URLSearchParams) {
search = this.buildSearchParams(options.search);
} else {
search = options.search;
}
if(search) {
key += "?" + search;
}
}
return key;
}
buildSearchParams(search:URLSearchParams):string {
let params:string[] = [];
search.paramsMap.forEach((v, k) => {
if(isUndefined(v) || isNull(v)) {
return;
}
params.push(`${k}=${v}`);
});
return params.join('&');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment