Skip to content

Instantly share code, notes, and snippets.

@partharanjan
Last active October 11, 2019 06:20
Show Gist options
  • Save partharanjan/ed74b65b6625fd9cafa11a83fb40e195 to your computer and use it in GitHub Desktop.
Save partharanjan/ed74b65b6625fd9cafa11a83fb40e195 to your computer and use it in GitHub Desktop.
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpResponse } from '@angular/common/http';
import { CacheService } from '../services/cache.service';
import { of } from 'rxjs';
import { tap } from 'rxjs/operators';
@Injectable()
export class CacheHttpInterceptor implements HttpInterceptor {
constructor(private cache: CacheService) { }
intercept(req: HttpRequest<any>, next: HttpHandler) {
if (!this.isRequestCachable(req)) {
return next.handle(req);
}
// check for cache request
const cachedResponse = this.cache.get(req);
if (cachedResponse !== null) {
return of(cachedResponse);
}
return next.handle(req).pipe(
tap(event => {
if (event instanceof HttpResponse) {
this.cache.set(req, event);
}
})
);
}
private isRequestCachable(req: HttpRequest<any>) {
return (req.method === 'GET');
}
}
import { Injectable } from '@angular/core';
import { HttpResponse, HttpRequest } from '@angular/common/http';
export interface CacheEntry {
url: string;
response: HttpResponse<any>
}
@Injectable()
export class CacheService {
constructor() { }
cacheMap = new Map<string, CacheEntry>();
get(req: HttpRequest<any>): HttpResponse<any> | null {
const entry = this.cacheMap.get(req.urlWithParams);
if (!entry) {
return null;
}
return entry.response;
}
set(req: HttpRequest<any>, res: HttpResponse<any>): void {
const entry: CacheEntry = { url: req.urlWithParams, response: res };
this.cacheMap.set(req.urlWithParams, entry);
}
clear() {
this.cacheMap.clear();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment