Skip to content

Instantly share code, notes, and snippets.

@UserGalileo
Created November 14, 2021 19:27
Show Gist options
  • Save UserGalileo/8f0b00e25b31ec5b199243d51705b6b5 to your computer and use it in GitHub Desktop.
Save UserGalileo/8f0b00e25b31ec5b199243d51705b6b5 to your computer and use it in GitHub Desktop.
Cache Interceptor
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