Ajout d'un système de cache des

requêtes HTTP
This commit is contained in:
Sébastien André
2019-11-19 22:42:43 +01:00
parent fb2699f974
commit 53ff769188
15 changed files with 257 additions and 164 deletions

View File

@@ -0,0 +1,39 @@
import { Injectable } from "@angular/core";
import {
HttpEvent,
HttpRequest,
HttpResponse,
HttpInterceptor,
HttpHandler
} from "@angular/common/http";
import { Observable } from "rxjs/Observable";
import { startWith, tap } from "rxjs/operators";
import "rxjs/add/observable/of";
import { RequestCache } from "./request-cache.service";
@Injectable()
export class CachingInterceptor implements HttpInterceptor {
constructor(private cache: RequestCache) {}
intercept(req: HttpRequest<any>, next: HttpHandler) {
const cachedResponse = this.cache.get(req);
return cachedResponse
? Observable.of(cachedResponse)
: this.sendRequest(req, next);
}
sendRequest(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
tap(event => {
if (event instanceof HttpResponse) {
this.cache.put(req, event);
}
})
);
}
}