perf: add promise deduplication for getAssetInfo (#134)
Add Promise deduplication (request coalescing) to the `getAssetInfo` method in `ImmichClient` (`lib/immich.ts`) to prevent concurrent identical requests from firing multiple times to the Immich server. This is particularly helpful when calling `Promise.all` on multiple assets concurrently (e.g. hero images on the homepage or multiple album cover placeholder hashes). Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
This commit is contained in:
@@ -74,6 +74,7 @@ class ImmichClient {
|
|||||||
private hasLoggedAlbums = false;
|
private hasLoggedAlbums = false;
|
||||||
private pendingAlbumsPromise: Promise<ImmichAlbum[]> | null = null;
|
private pendingAlbumsPromise: Promise<ImmichAlbum[]> | null = null;
|
||||||
private pendingAlbumPromises = new Map<string, Promise<ImmichAlbum | null>>();
|
private pendingAlbumPromises = new Map<string, Promise<ImmichAlbum | null>>();
|
||||||
|
private pendingAssetPromises = new Map<string, Promise<ImmichAsset | null>>();
|
||||||
|
|
||||||
private get config() {
|
private get config() {
|
||||||
return getConfig();
|
return getConfig();
|
||||||
@@ -344,11 +345,27 @@ class ImmichClient {
|
|||||||
const cached = cache.get<ImmichAsset>(cacheKey);
|
const cached = cache.get<ImmichAsset>(cacheKey);
|
||||||
if (cached) return cached;
|
if (cached) return cached;
|
||||||
|
|
||||||
const asset = await this.request<ImmichAsset>(`/assets/${encodeURIComponent(assetId)}`);
|
// ⚡ Bolt: Deduplicate concurrent requests for the same asset ID.
|
||||||
if (!asset) return null;
|
// If a request for this asset is already in flight (e.g. from Promise.all in a grid),
|
||||||
|
// return the pending promise instead of triggering a redundant API call.
|
||||||
|
if (this.pendingAssetPromises.has(assetId)) {
|
||||||
|
return this.pendingAssetPromises.get(assetId)!;
|
||||||
|
}
|
||||||
|
|
||||||
cache.set(cacheKey, asset, this.config.cacheTtl);
|
const promise = (async () => {
|
||||||
return asset;
|
try {
|
||||||
|
const asset = await this.request<ImmichAsset>(`/assets/${encodeURIComponent(assetId)}`);
|
||||||
|
if (!asset) return null;
|
||||||
|
|
||||||
|
cache.set(cacheKey, asset, this.config.cacheTtl);
|
||||||
|
return asset;
|
||||||
|
} finally {
|
||||||
|
this.pendingAssetPromises.delete(assetId);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
this.pendingAssetPromises.set(assetId, promise);
|
||||||
|
return promise;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
Reference in New Issue
Block a user