All files / src/composables useImageUrlCache.ts

94.87% Statements 37/39
91.66% Branches 22/24
88.88% Functions 8/9
97.22% Lines 35/36

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89                41x 41x       41x 41x     149x 149x 137x   26x 26x 24x   26x           24x 24x 11x   13x         156x   155x 155x 3x     152x 152x   149x 146x       146x 146x     149x 149x         9x 9x 9x 9x 9x             3x         187x 187x            
import api from '@/services/api'
 
interface CacheEntry {
  url: string
  expiresAt: number
}
 
// Presigned S3 read URLs expire in 1 hour server-side — refresh at 55 min.
const PRESIGNED_URL_TTL_MS = 55 * 60 * 1000
const FAILED_URL_TTL_MS = 60 * 1000
 
// Module-level (not per-component) so every ImageField/ImageCarousel/member
// card/entity card instance shares the same cache and in-flight requests.
const urlCache = new Map<string, CacheEntry>()
const inFlight = new Map<string, Promise<string>>()
 
async function fetchPresignedUrl(key: string): Promise<string> {
  try {
    const response = await api.post('/v1/upload/presigned-read-url', { key })
    return response.data?.readUrl || ''
  } catch (error) {
    const status = (error as any)?.response?.status
    if (status !== 404) {
      console.error('Error getting presigned read URL for key:', key, error)
    }
    return ''
  }
}
 
/** Synchronous read of an unexpired cache entry, for template use without awaiting. */
export function getCachedImageUrl(key: string): string | undefined {
  const cached = urlCache.get(key)
  if (cached && Date.now() < cached.expiresAt) {
    return cached.url
  }
  return undefined
}
 
/** Cache-or-fetch a presigned read URL for an S3 key, deduping concurrent requests. */
export function resolveImageUrl(key: string): Promise<string> {
  if (!key) return Promise.resolve('')
 
  const cached = urlCache.get(key)
  if (cached && Date.now() < cached.expiresAt) {
    return Promise.resolve(cached.url)
  }
 
  const existing = inFlight.get(key)
  if (existing) return existing
 
  const promise = fetchPresignedUrl(key).then((url) => {
    urlCache.set(key, {
      url,
      expiresAt: Date.now() + (url ? PRESIGNED_URL_TTL_MS : FAILED_URL_TTL_MS)
    })
    inFlight.delete(key)
    return url
  })
 
  inFlight.set(key, promise)
  return promise
}
 
/** Fire-and-forget resolve + warm the browser's own HTTP image cache. */
export function preloadImageUrl(key: string): void {
  Iif (!key) return
  void resolveImageUrl(key).then((url) => {
    Eif (url && typeof Image !== 'undefined') {
      const img = new Image()
      img.src = url
    }
  })
}
 
/** Drop a cached entry so the next resolve re-fetches instead of reusing a stale URL. */
export function invalidateImageUrl(key: string): void {
  urlCache.delete(key)
}
 
/** Test-only: clears all cached/in-flight state so cases in a shared test file don't leak. */
export function __resetImageUrlCacheForTests(): void {
  urlCache.clear()
  inFlight.clear()
}
 
export function useImageUrlCache() {
  return { resolveImageUrl, preloadImageUrl, getCachedImageUrl, invalidateImageUrl }
}