42 lines
1.5 KiB
TypeScript
42 lines
1.5 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 readonly _cacheApiService: CacheApiService) {}
|
|
|
|
intercept(req: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
|
|
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<any>, next: HttpHandler): Observable<HttpEvent<any>> {
|
|
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);
|
|
}
|
|
}),
|
|
);
|
|
}
|
|
}
|