library:
jszip - const zip = jszip()
file-saver - saveAs(content, `${fetchListingId}.zip`)
issue: cors -
the original plan was download photos from the front end and zip with jszip, but got cors error when download from firebase storage
solutions:
1. on graphql, add query: getPhotosBuffer(listingId: String): [PhotoBuffer] to return stringified buffer of photos
fetchPhotosBuffer = async (listingId: string): Promise<PhotoBuffer[]> =>
this.cacheProvider.processor<PhotoBuffer[]>(
async () => {
const photos = await this.collection
.where('listingId', '==', listingId)
.orderBy('orders')
.get()
const result: PhotoBuffer[] = []
await Promise.all(
photos.docs.map(async (photo: any) => {
const data = photo.data()
const { photoUrl } = data
try {
const buffer = await axios
.get(photoUrl, {
responseType: 'arraybuffer',
})
.then(response => Buffer.from(response.data, 'binary'))
result.push({ id: photo.id, data: buffer.toString() })
} catch (err) {
console.log(err)
}
})
)
return result
},
{ key: `${this.cachePrefix}-fetchPhotos-${listingId}` }
)
useEffect(() => {
const fetchPhotos = async () => {
const result = await client.query({
query: QUERY_LISTING_PHOTOS_BUFFER,
variables: { listingId: fetchListingId },
})
const {
data: { getPhotosBuffer },
} = result
getPhotosBuffer.forEach((photo: any) => {
zip.file(`${photo.id}.jpg`, JSON.parse(photo.data).data, {
binary: true,
})
})
zip
.generateAsync({
type: 'blob',
})
.then(content => {
saveAs(content, `${fetchListingId}.zip`)
})
.finally(() => setFetchListingId(''))
}
if (fetchListingId) {
fetchPhotos()
}
}, [fetchListingId, client, zip])
Comments
Post a Comment