Petits fix sur le cache des requêtes Http

This commit is contained in:
Sébastien André
2019-11-20 10:46:43 +01:00
parent 53ff769188
commit 3a66d5e6ac
2 changed files with 29 additions and 19 deletions

View File

@@ -1,17 +1,17 @@
import { Injectable } from "@angular/core";
import { Injectable } from '@angular/core';
import {
HttpEvent,
HttpRequest,
HttpResponse,
HttpInterceptor,
HttpHandler
} from "@angular/common/http";
} from '@angular/common/http';
import { Observable } from "rxjs/Observable";
import { startWith, tap } from "rxjs/operators";
import "rxjs/add/observable/of";
import { Observable } from 'rxjs/Observable';
import { startWith, tap } from 'rxjs/operators';
import 'rxjs/add/observable/of';
import { RequestCache } from "./request-cache.service";
import { RequestCache } from './request-cache.service';
@Injectable()
export class CachingInterceptor implements HttpInterceptor {

View File

@@ -1,31 +1,41 @@
import { Injectable } from "@angular/core";
import { HttpRequest, HttpResponse } from "@angular/common/http";
import { Injectable } from '@angular/core';
import { HttpRequest, HttpResponse } from '@angular/common/http';
const maxAge = 30000;
@Injectable()
export class RequestCache {
cache = new Map();
private cache: Map<string, any>;
get(req: HttpRequest<any>): HttpResponse<any> | undefined {
const url = req.urlWithParams + "-" + req.method;
const cached = this.cache.get(url);
if (!cached) {
return undefined;
constructor() {
this.cache = new Map<string, any>();
}
return cached.response;
get(req: HttpRequest<any>): HttpResponse<any> | undefined {
const splittedUrl = req.urlWithParams.split('/');
const url = splittedUrl[splittedUrl.length - 1] + '_' + req.method;
this.clearExpiredEntries();
const cached = this.cache.get(url);
let cachedResponse: HttpResponse<any>;
if (cached) {
cachedResponse = cached.response;
}
return cachedResponse;
}
put(req: HttpRequest<any>, response: HttpResponse<any>): void {
//const url = req.url;
const url = req.urlWithParams + "-" + req.method;
const splittedUrl = req.urlWithParams.split('/');
const url = splittedUrl[splittedUrl.length - 1] + '_' + req.method;
const entry = { url, response, lastRead: Date.now() };
this.cache.set(url, entry);
this.clearExpiredEntries();
}
console.log(this.cache);
private clearExpiredEntries(): void {
const maxAge = 30000;
const expired = Date.now() - maxAge;
this.cache.forEach(expiredEntry => {
if (expiredEntry.lastRead < expired) {
this.cache.delete(expiredEntry.url);