Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevented duplicated parallel HTTP calls #18

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 20 additions & 12 deletions src/app/interceptors/cache.interceptor.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpResponse } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { Observable } from 'rxjs';
import { CacheService } from '../services/cache.service';
import { tap } from 'rxjs/operators';
import { filter, first, map, shareReplay } from 'rxjs/operators';

@Injectable()
export class CacheInterceptor implements HttpInterceptor {
constructor(private readonly cacheService: CacheService) {}

public readonly store: Record<string, Observable<HttpEvent<any>>> = {};

intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
// Don't cache if it's not a GET request
if (request.method !== 'GET') {
Expand All @@ -26,20 +28,26 @@ export class CacheInterceptor implements HttpInterceptor {
// Checked if there is cached data for this URI
const cachedResponse = this.cacheService.getFromCache(request);
if (cachedResponse) {
// In case of parallel requests to same URI,
// return the request already in progress
// otherwise return the last cached data
return cachedResponse instanceof Observable ? cachedResponse : of(cachedResponse.clone());
return cachedResponse;
}

// If the request of going through for first time
// then let the request proceed and cache the response
return next.handle(request).pipe(
tap(event => {
if (event instanceof HttpResponse) {
this.cacheService.addToCache(request, event);
}
})
const response = next.handle(request).pipe(
filter(res => res instanceof HttpResponse),
// The default Observable behavior is creating a new stream for each subscription.
// With shareReplay we avoid the default behavior and instead we execute the stream only once,
// then the result of that stream will be replayed to each new subscriber.
shareReplay(1)
);
this.cacheService.addToCache(request, response);
return response.pipe(
// Ensures that when the first value is received, the observable will automatically unsubscribe
// and stop listening for any further emissions.
first(),
// Clones the response, to avoid that further modifications to the data will affect the data
// within the cache.
map(event => (event as HttpResponse<any>).clone())
);
}
}
9 changes: 5 additions & 4 deletions src/app/services/cache.service.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { HttpRequest, HttpResponse } from '@angular/common/http';
import { HttpEvent, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

interface Cache {
response: HttpResponse<any>;
response: Observable<HttpEvent<any>>;
time: number;
}

Expand All @@ -12,14 +13,14 @@ const MAX_CACHE_AGE = 5 * 60 * 1000; // 5 minuti
export class CacheService {
cacheMap = new Map<string, Cache>();

getFromCache(req: HttpRequest<any>): HttpResponse<any> | undefined {
getFromCache(req: HttpRequest<any>): Observable<HttpEvent<any>> | undefined {
const cached = this.cacheMap.get(req.urlWithParams);

if (!cached || Date.now() - cached.time > MAX_CACHE_AGE) return undefined;
return cached.response;
}

addToCache(req: HttpRequest<any>, response: HttpResponse<any>): void {
addToCache(req: HttpRequest<any>, response: Observable<HttpEvent<any>>): void {
this.cacheMap.set(req.url, { response, time: Date.now() });
}
}