This commit is contained in:
parent
c29caf01c8
commit
9d80345b77
7 changed files with 332 additions and 15 deletions
78
src/api/merchImages.js
Normal file
78
src/api/merchImages.js
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
import { apiClient } from '@/services/apiClient.js'
|
||||
|
||||
export const useMerchImagesApi = () => {
|
||||
const uploadImage = async (uuid, file) => {
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
formData.append('imageType', 'all')
|
||||
|
||||
try {
|
||||
const response = await apiClient.post(`/merch/images/${uuid}`, formData)
|
||||
|
||||
if (response.status !== 200) {
|
||||
throw new Error(`Upload failed: ${response.status}`)
|
||||
}
|
||||
|
||||
return response.data
|
||||
} catch (error) {
|
||||
console.error('Upload failed:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const cachedImages = new Map() // Map<uuid, { etag, url }>
|
||||
const getImageUrl = async (uuid, type) => {
|
||||
try {
|
||||
const response = await apiClient.get(`/merch/images/${uuid}`, { type })
|
||||
|
||||
if (response.status !== 200) {
|
||||
throw new Error(`Get image failed: ${response.status}`)
|
||||
}
|
||||
|
||||
const { link, ETag } = response.data
|
||||
|
||||
if (cachedImages.has(uuid) && cachedImages.get(uuid).etag === ETag) {
|
||||
return cachedImages.get(uuid)
|
||||
}
|
||||
|
||||
const res = await fetch(link)
|
||||
if (!res.ok) throw new Error(`Failed to load image: ${res.status}`)
|
||||
|
||||
const blob = await res.blob()
|
||||
const imgUrl = URL.createObjectURL(blob)
|
||||
|
||||
cachedImages.set(uuid, { imgUrl, etag: ETag })
|
||||
return { imgUrl, etag: ETag }
|
||||
|
||||
} catch (error) {
|
||||
console.error('Get image failed:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const deleteImage = async (uuid) => {
|
||||
try {
|
||||
const response = await apiClient.delete(`/merch/images/${uuid}`)
|
||||
if (response.status !== 200) {
|
||||
throw new Error(`Delete failed: ${response.status}`)
|
||||
}
|
||||
|
||||
if (cachedImages.has(uuid)) {
|
||||
const cached = cachedImages.get(uuid)
|
||||
if (cached.imgUrl?.startsWith('blob:')) URL.revokeObjectURL(cached.imgUrl)
|
||||
cachedImages.delete(uuid)
|
||||
}
|
||||
|
||||
return true
|
||||
} catch (error) {
|
||||
console.error('Delete image failed:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
uploadImage,
|
||||
getImageUrl,
|
||||
deleteImage,
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue