Created
November 14, 2021 19:27
-
-
Save UserGalileo/8f0b00e25b31ec5b199243d51705b6b5 to your computer and use it in GitHub Desktop.
Cache Interceptor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
import { | |
HttpRequest, HttpResponse, | |
HttpInterceptor, HttpHandler | |
} from '@angular/common/http'; | |
import { of } from 'rxjs'; | |
import { startWith, tap } from 'rxjs/operators'; | |
@Injectable() | |
export class CacheInterceptor implements HttpInterceptor { | |
private cache = new Map<string, any>(); | |
intercept(req: HttpRequest<any>, next: HttpHandler) { | |
if (!this.isCacheable(req)) { return next.handle(req); } | |
const cachedResponse = this.cache.get(req.urlWithParams); | |
// V1 - Return cache if present | |
return cachedResponse | |
? of(cachedResponse) | |
: this.sendRequest(req, next); | |
// V2 - Return cache first, then request | |
return cachedResponse | |
? this.sendRequest(req, next).pipe(startWith(cachedResponse)) | |
: this.sendRequest(req, next); | |
} | |
private sendRequest( | |
req: HttpRequest<any>, | |
next: HttpHandler, | |
) { | |
return next.handle(req).pipe( | |
tap(event => { | |
if (event instanceof HttpResponse) { | |
this.cache.set(req.urlWithParams, event); | |
} | |
}) | |
); | |
} | |
private isCacheable(req: HttpRequest<any>) { | |
return req.method === 'GET'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment