-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.interceptor.ts
49 lines (40 loc) · 1.46 KB
/
cache.interceptor.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpResponse } from '@angular/common/http';
import { Observable, of, from } from 'rxjs';
import { switchMap, map } from 'rxjs/operators';
import * as localForage from 'localforage';
import * as moment from 'moment';
@Injectable()
export abstract class CacheInterceptor implements HttpInterceptor {
private cacheTime: number = 60;
constructor() { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const url = request.url.replace('https://', '').replace(/[^0-9a-z]/g, '');
return from(localForage.keys()).pipe(
switchMap((keys) => this.getFromCache(keys, url)),
switchMap((cache) => cache
? of(cache)
: next.handle(request).pipe(switchMap((data) => this.addToCache(data, url)))),
);
}
getFromCache(keys, url): Observable<any> | null {
if (!keys.includes(url)) {
return of(null);
}
return from(localForage.getItem(url)).pipe(
switchMap((item) => this.isExpired(item))
)
}
addToCache(data, url) {
const value = {
body: data.body,
date: moment().format(),
};
return of(localForage.setItem(url, value)).pipe(map(() => data));
}
isExpired(item: any) {
const outOfDate = moment().diff(moment(item.date), 'minutes') > this.cacheTime;
const resp = new HttpResponse({ body: item.body });
return of(outOfDate ? null : resp);
}
}