Skip to content

Commit

Permalink
perf: cache api requests
Browse files Browse the repository at this point in the history
  • Loading branch information
GeorgeHulpoi committed Feb 10, 2024
1 parent e9362a8 commit 6b2ec42
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 19 deletions.
2 changes: 1 addition & 1 deletion projects/ngx-payload-live-preview/package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
10 changes: 5 additions & 5 deletions projects/ngx-payload-live-preview/src/lib/service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
describe('PayloadLivePreviewService', () => {
it('empty', () => {
expect(true).toBeTruthy();
});
});
describe('PayloadLivePreviewService', () => {
it('empty', () => {
expect(true).toBeTruthy();
});
});
35 changes: 22 additions & 13 deletions projects/ngx-payload-live-preview/src/lib/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export class PayloadLivePreviewService {
optional: true,
});
private readonly httpClient = inject(HttpClient);
private readonly cacheFetch: Map<string, object> = new Map();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private base$: Observable<any>;

Expand Down Expand Up @@ -427,22 +428,30 @@ export class PayloadLivePreviewService {
this.apiRoute || '/api'
}/${collection}/${id}?depth=${depth}`;

return this.httpClient
.get(url, {
let res$: Observable<object>;

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);
}),
);
}
}

0 comments on commit 6b2ec42

Please sign in to comment.