Files
JayuCloud/JC-ArtList-Frontend/src/utils/signed-image-cache.ts
T

132 lines
4.1 KiB
TypeScript

import { fileApi } from '@/api/file'
import type { IdType } from '@/utils/id'
const SIGNED_IMAGE_CACHE_TTL_MS = 10 * 60 * 1000
export type SignedImageSource = 'public'
type SignedImageCacheEntry = {
url: string
expiresAt: number
}
const signedImageUrlCache = new Map<string, SignedImageCacheEntry>()
const pendingSignedImageUrlRequests = new Map<string, Promise<string>>()
const normalizeFileId = (fileId: IdType | null | undefined) => String(fileId ?? '').trim()
const buildCacheKey = (source: SignedImageSource, fileId: string) => `${source}:${fileId}`
const normalizeImageUrl = (url: string): string => {
const trimmedUrl = url.trim()
if (!trimmedUrl) return ''
if (/^(https?:)?\/\//i.test(trimmedUrl) || /^(data|blob):/i.test(trimmedUrl) || trimmedUrl.startsWith('/')) {
return trimmedUrl
}
return `http://${trimmedUrl}`
}
const requestSignedImageUrl = (_source: SignedImageSource, fileId: string): Promise<string> => {
return fileApi.getSignedUrl(fileId).then(response => String(response.data || ''))
}
const getUsableCacheEntry = (key: string) => {
const cached = signedImageUrlCache.get(key)
if (!cached) return undefined
if (cached.expiresAt <= Date.now()) {
signedImageUrlCache.delete(key)
return undefined
}
return cached.url
}
export const parseImageFileIds = (value?: string | null): string[] =>
String(value || '')
.split(',')
.map(id => id.trim())
.filter(Boolean)
export const getCachedSignedImageUrlSync = (
fileId: IdType | null | undefined,
source: SignedImageSource = 'public'
): string => {
const fileIdKey = normalizeFileId(fileId)
if (!fileIdKey) return ''
return getUsableCacheEntry(buildCacheKey(source, fileIdKey)) || ''
}
export const getCachedSignedImageUrl = async (
fileId: IdType | null | undefined,
fallback = '',
source: SignedImageSource = 'public'
): Promise<string> => {
const fileIdKey = normalizeFileId(fileId)
if (!fileIdKey) return fallback
const key = buildCacheKey(source, fileIdKey)
const cachedUrl = getUsableCacheEntry(key)
if (cachedUrl) return cachedUrl
const pendingRequest = pendingSignedImageUrlRequests.get(key)
if (pendingRequest) {
return pendingRequest.then(url => url || fallback).catch(() => fallback)
}
const request = requestSignedImageUrl(source, fileIdKey)
.then(response => {
const url = normalizeImageUrl(String(response || ''))
if (url) {
signedImageUrlCache.set(key, {
url,
expiresAt: Date.now() + SIGNED_IMAGE_CACHE_TTL_MS
})
}
return url
})
.finally(() => {
pendingSignedImageUrlRequests.delete(key)
})
pendingSignedImageUrlRequests.set(key, request)
return request.then(url => url || fallback).catch(() => fallback)
}
export const clearCachedSignedImageUrl = (
fileId: IdType | null | undefined,
source: SignedImageSource = 'public'
): void => {
const fileIdKey = normalizeFileId(fileId)
if (!fileIdKey) return
const cacheKey = buildCacheKey(source, fileIdKey)
signedImageUrlCache.delete(cacheKey)
pendingSignedImageUrlRequests.delete(cacheKey)
}
export const refreshCachedSignedImageUrl = async (
fileId: IdType | null | undefined,
fallback = '',
source: SignedImageSource = 'public'
): Promise<string> => {
clearCachedSignedImageUrl(fileId, source)
return getCachedSignedImageUrl(fileId, fallback, source)
}
export const getCachedSignedImageUrls = async (
fileIds: Array<IdType | null | undefined>,
fallback = '',
source: SignedImageSource = 'public'
): Promise<string[]> => {
const urls = await Promise.all(fileIds.map(fileId => getCachedSignedImageUrl(fileId, '', source)))
const validUrls = urls.filter(Boolean)
return validUrls.length ? validUrls : (fallback ? [fallback] : [])
}
export const getCachedSignedImageUrlsSync = (
fileIds: Array<IdType | null | undefined>,
source: SignedImageSource = 'public'
): string[] =>
fileIds.map(fileId => getCachedSignedImageUrlSync(fileId, source)).filter(Boolean)
export const extractLegacyFileId = (value?: string | null): string => {
const source = String(value || '').replace(/<[^>]*>/g, '')
return source.match(/\/api\/file\/get\/([^/?#"'<>]+)/)?.[1] || ''
}