44 lines
1.6 KiB
TypeScript
44 lines
1.6 KiB
TypeScript
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
|
|
import { Injectable } from '@angular/core';
|
|
import { Observable } from 'rxjs';
|
|
import { CacheApiService } from './cache-api.service';
|
|
import { catchError, tap } from 'rxjs/operators';
|
|
|
|
@Injectable()
|
|
export class HttpCacheInterceptor implements HttpInterceptor {
|
|
constructor(private _cacheApiService: CacheApiService) {}
|
|
|
|
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
|
|
// continue if not cachable.
|
|
if (!this._cacheApiService.isCachable(req)) {
|
|
return next.handle(req);
|
|
}
|
|
|
|
return this._cacheApiService.getCachedRequest(req).pipe(
|
|
tap(() => {
|
|
// console.log('[CACHE-API] got from cache', ok);
|
|
}),
|
|
catchError(() =>
|
|
// console.log("[CACHE-API] Cache fetch error", cacheError, req.url);
|
|
this.sendRequest(req, next),
|
|
),
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Get server response observable by sending request to `next()`.
|
|
* Will add the response to the cache on the way out.
|
|
*/
|
|
sendRequest(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
|
|
// console.log('[CACHE-API] request', request.url);
|
|
return next.handle(request).pipe(
|
|
tap(event => {
|
|
// There may be other events besides the response.
|
|
if (event instanceof HttpResponse) {
|
|
this._cacheApiService.cacheRequest(request, event);
|
|
}
|
|
}),
|
|
);
|
|
}
|
|
}
|