From 6b2ec42572c0edd60b6d1ed2b6959c3ffde39614 Mon Sep 17 00:00:00 2001 From: George-Valentin Hulpoi Date: Sat, 10 Feb 2024 22:21:05 +0200 Subject: [PATCH] perf: cache api requests --- .../ngx-payload-live-preview/package.json | 2 +- .../src/lib/service.spec.ts | 10 +++--- .../src/lib/service.ts | 35 ++++++++++++------- 3 files changed, 28 insertions(+), 19 deletions(-) diff --git a/projects/ngx-payload-live-preview/package.json b/projects/ngx-payload-live-preview/package.json index 2fc75e2..f4a8102 100644 --- a/projects/ngx-payload-live-preview/package.json +++ b/projects/ngx-payload-live-preview/package.json @@ -1,6 +1,6 @@ { "name": "ngx-payload-live-preview", - "version": "17.0.0-alpha.1", + "version": "17.0.0-alpha.2", "peerDependencies": { "@angular/common": "^17.0.0", "@angular/core": "^17.0.0", diff --git a/projects/ngx-payload-live-preview/src/lib/service.spec.ts b/projects/ngx-payload-live-preview/src/lib/service.spec.ts index 59b2532..f03dc6b 100644 --- a/projects/ngx-payload-live-preview/src/lib/service.spec.ts +++ b/projects/ngx-payload-live-preview/src/lib/service.spec.ts @@ -1,5 +1,5 @@ -describe('PayloadLivePreviewService', () => { - it('empty', () => { - expect(true).toBeTruthy(); - }); -}); +describe('PayloadLivePreviewService', () => { + it('empty', () => { + expect(true).toBeTruthy(); + }); +}); diff --git a/projects/ngx-payload-live-preview/src/lib/service.ts b/projects/ngx-payload-live-preview/src/lib/service.ts index 4da7814..59d323c 100644 --- a/projects/ngx-payload-live-preview/src/lib/service.ts +++ b/projects/ngx-payload-live-preview/src/lib/service.ts @@ -27,6 +27,7 @@ export class PayloadLivePreviewService { optional: true, }); private readonly httpClient = inject(HttpClient); + private readonly cacheFetch: Map = new Map(); // eslint-disable-next-line @typescript-eslint/no-explicit-any private base$: Observable; @@ -427,22 +428,30 @@ export class PayloadLivePreviewService { this.apiRoute || '/api' }/${collection}/${id}?depth=${depth}`; - return this.httpClient - .get(url, { + let res$: Observable; + + if (this.cacheFetch.has(url)) { + res$ = of(this.cacheFetch.get(url)!); + } else { + res$ = this.httpClient.get(url, { withCredentials: true, headers: { 'Content-Type': 'application/json', }, - }) - .pipe( - tap((res) => { - ref[accessor] = res; - }), - map(() => undefined), - catchError((err) => { - console.error(err); - return of(undefined); - }), - ); + }).pipe( + tap((res) => this.cacheFetch.set(url, res)) + ) + } + + return res$.pipe( + tap((res) => { + ref[accessor] = res; + }), + map(() => undefined), + catchError((err) => { + console.error(err); + return of(undefined); + }), + ); } }