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 | 14x 14x 14x 14x 4x 4x 3x 1x 1x 1x 7x 6x 6x 1x 5x 5x 4x 4x 4x 4x 4x 4x | 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 so every FileField instance shares the same cache and
// in-flight requests, mirroring useImageUrlCache.ts.
const urlCache = new Map<string, CacheEntry>()
const inFlight = new Map<string, Promise<string>>()
async function fetchPresignedUrl(key: string, fileName: string): Promise<string> {
try {
// `download: true` forces Content-Disposition: attachment server-side —
// a generic uploaded file should never render inline in the browser
// (see uploads/presigned-read-url.js).
const response = await api.post('/v1/upload/presigned-read-url', {
key,
download: true,
fileName
})
return response.data?.readUrl || ''
} catch (error) {
const status = (error as any)?.response?.status
Iif (status !== 404) {
console.error('Error getting presigned read URL for key:', key, error)
}
return ''
}
}
/** Cache-or-fetch a presigned download URL for a file's S3 key, deduping concurrent requests. */
export function resolveFileUrl(key: string, fileName: 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, fileName).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
}
/** Test-only: clears all cached/in-flight state so cases in a shared test file don't leak. */
export function __resetFileUrlCacheForTests(): void {
urlCache.clear()
inFlight.clear()
}
export function useFileUrlCache() {
return { resolveFileUrl }
}
|