Browse Source

Add in a quick cache

master
Dan 2 years ago
parent
commit
013d2d6338
  1. 11
      src/app/app.config.ts
  2. 33
      src/app/interceptors/httpCache.interceptor.ts

11
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
}
]
};

33
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<string, any>();
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// 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);
}
})
);
}
}
Loading…
Cancel
Save