Skip to content

Commit 12ffad7

Browse files
committed
🧤 request and response caching
1 parent cacc368 commit 12ffad7

File tree

3 files changed

+80
-0
lines changed

3 files changed

+80
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ This project was generated with [Angular CLI](https://github.com/angular/angular
1111
- Angular Material (https://material.angular.io/guide/getting-started)
1212
- Angular Universal (https://angular.io/guide/universal)
1313
- Webpack
14+
- Web Caching
1415

1516
## Development server
1617

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import { Injectable } from '@angular/core';
2+
import {
3+
HttpRequest,
4+
HttpHandler,
5+
HttpEvent,
6+
HttpInterceptor, HttpResponse
7+
} from '@angular/common/http';
8+
import {Observable, of} from 'rxjs';
9+
import {tap} from 'rxjs/operators';
10+
import {HttpCacheService} from '../services/http-cache/http-cache.service';
11+
12+
@Injectable()
13+
export class CachingInterceptor implements HttpInterceptor {
14+
15+
constructor(private httpCacheService: HttpCacheService) {}
16+
17+
public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
18+
19+
if (request.method !== 'GET') {
20+
return next.handle(request);
21+
}
22+
23+
if (request.headers.get('cache') === 'clear') {
24+
this.httpCacheService.clearCache();
25+
}
26+
27+
if (request.headers.get('cache') === 'reset') {
28+
this.httpCacheService.delete(request.urlWithParams);
29+
}
30+
31+
const cachedResponse = this.httpCacheService.get(request.urlWithParams);
32+
33+
if (cachedResponse) {
34+
return of(cachedResponse.clone());
35+
}
36+
37+
/**
38+
* request is going for the first time then let the request process
39+
* and cache the response
40+
*/
41+
return next.handle(request).pipe(
42+
tap( (event) => {
43+
if (event instanceof HttpResponse) {
44+
this.httpCacheService.set(request.urlWithParams, event.clone());
45+
}
46+
})
47+
);
48+
49+
}
50+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { Injectable } from '@angular/core';
2+
import { HttpResponse } from '@angular/common/http';
3+
4+
@Injectable({
5+
providedIn: 'root'
6+
})
7+
export class HttpCacheService {
8+
9+
private cache: Map<string, HttpResponse<any>> = new Map<string, HttpResponse<any>>();
10+
11+
constructor() { }
12+
13+
public get(url: string): HttpResponse<any> | undefined {
14+
return this.cache[url];
15+
}
16+
17+
public set(url: string, response: HttpResponse<any>): void {
18+
this.cache[url] = response;
19+
}
20+
21+
public clearCache(): void {
22+
this.cache = new Map<string, HttpResponse<any>>();
23+
}
24+
25+
public delete(url: string): void {
26+
delete this.cache[url];
27+
}
28+
29+
}

0 commit comments

Comments
 (0)