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 readonly _cacheApiService: CacheApiService) {} intercept(req: HttpRequest, next: HttpHandler): Observable> { if (!this._cacheApiService.isCachable(req)) { return next.handle(req); } return this._cacheApiService.getCachedRequest(req).pipe( // tap(ok => { // console.log('[CACHE-API] got from cache', ok); // }), catchError(cacheError => { // console.log('[CACHE-API] Cache fetch error', cacheError, req.url); return 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, next: HttpHandler): Observable> { return next.handle(request).pipe( tap(async event => { // There may be other events besides the response. if (event instanceof HttpResponse) { await this._cacheApiService.cacheRequest(request, event); } }), ); } }