From 013d2d63389eba200b959d762b0bbe9b6da98ab4 Mon Sep 17 00:00:00 2001 From: Dan Date: Tue, 12 Mar 2024 15:26:24 +0000 Subject: [PATCH] Add in a quick cache --- src/app/app.config.ts | 11 +++++-- src/app/interceptors/httpCache.interceptor.ts | 33 +++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) create mode 100644 src/app/interceptors/httpCache.interceptor.ts diff --git a/src/app/app.config.ts b/src/app/app.config.ts index 13300a0..aa19e9e 100644 --- a/src/app/app.config.ts +++ b/src/app/app.config.ts @@ -1,13 +1,20 @@ import { ApplicationConfig } from '@angular/core'; import { provideRouter } from '@angular/router'; -import { provideHttpClient } from '@angular/common/http'; +import { HTTP_INTERCEPTORS, provideHttpClient, withInterceptors, withInterceptorsFromDi } from '@angular/common/http'; import { routes } from './app.routes'; import { provideAnimationsAsync } from '@angular/platform-browser/animations/async'; +import { CacheInterceptor } from './interceptors/httpCache.interceptor'; export const appConfig: ApplicationConfig = { providers: [ provideRouter(routes), - provideHttpClient(), provideAnimationsAsync() + provideHttpClient(withInterceptorsFromDi()), + provideAnimationsAsync(), + { + provide: HTTP_INTERCEPTORS, + useClass: CacheInterceptor, + multi: true + } ] }; diff --git a/src/app/interceptors/httpCache.interceptor.ts b/src/app/interceptors/httpCache.interceptor.ts new file mode 100644 index 0000000..833dd67 --- /dev/null +++ b/src/app/interceptors/httpCache.interceptor.ts @@ -0,0 +1,33 @@ +import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from "@angular/common/http"; +import { Injectable } from "@angular/core"; +import { Observable, of, tap } from "rxjs"; + +@Injectable() +export class CacheInterceptor implements HttpInterceptor { + private cache = new Map(); + + intercept(req: HttpRequest, next: HttpHandler): Observable> { + // Only cache GET requests + if (req.method !== 'GET') { + return next.handle(req); + } + + const cachedResponse = this.cache.get(req.urlWithParams); + if (cachedResponse) { + // Serve from cache + console.log("cache hit") + return of(cachedResponse); + } + + console.log("cache miss") + + return next.handle(req).pipe( + tap(event => { + if (event instanceof HttpResponse) { + // Cache the new response + this.cache.set(req.urlWithParams, event); + } + }) + ); + } +} \ No newline at end of file