feat(bucket): auto-create buckets and move files from temp to main buckets on property save
deploy-chabokan / deploy (push) Canceled after 0s
deploy-chabokan / deploy (push) Canceled after 0s
This commit is contained in:
@@ -135,12 +135,54 @@ const getMultipleSignedUrls = async (fileNameArray, bucketName) => {
|
||||
|
||||
const moveFromTempToMain = async (files, targetBucket) => {
|
||||
const tempBucket = 'temp'
|
||||
|
||||
for (const file of files) {
|
||||
await copyObject(targetBucket, file, `${tempBucket}/${file}`)
|
||||
|
||||
await removeObject(tempBucket, file)
|
||||
if (!files || !Array.isArray(files) || files.length === 0) {
|
||||
return []
|
||||
}
|
||||
|
||||
const { ensureBucketsExist, minioClient } = require('../../utils/upload/bucket')
|
||||
await ensureBucketsExist([tempBucket, targetBucket]).catch(() => {})
|
||||
|
||||
const updatedUrls = []
|
||||
|
||||
for (const item of files) {
|
||||
const rawStr = typeof item === 'object' && item !== null ? (item.url || item.fileName || item.name || '') : String(item || '')
|
||||
const fileName = getLastUrlSegment(rawStr)
|
||||
|
||||
if (!fileName) {
|
||||
continue
|
||||
}
|
||||
|
||||
try {
|
||||
// Check if object exists in temp bucket
|
||||
const existsInTemp = await minioClient.statObject(tempBucket, fileName).then(() => true).catch(() => false)
|
||||
if (existsInTemp) {
|
||||
// Copy object from temp to targetBucket
|
||||
await copyObject(targetBucket, fileName, `/${tempBucket}/${fileName}`)
|
||||
// Remove from temp bucket
|
||||
await removeObject(tempBucket, fileName)
|
||||
// Update File record in database if exists
|
||||
await File.findOneAndUpdate({ fileName }, { bucketName: targetBucket }, null).catch(() => {})
|
||||
}
|
||||
|
||||
// Construct new URL for targetBucket
|
||||
const protocol = process.env.AWS_USE_SSL === 'true' ? 'https://' : 'http://'
|
||||
const endpoint = process.env.AWS_ENDPOINT || 'localhost'
|
||||
const hostPort = (endpoint.includes(':') || !process.env.AWS_PORT) ? endpoint : `${endpoint}:${process.env.AWS_PORT}`
|
||||
const fullHost = hostPort.startsWith('http://') || hostPort.startsWith('https://') ? hostPort : `${protocol}${hostPort}`
|
||||
const newUrl = `${fullHost.replace(/\/$/, '')}/${targetBucket}/${fileName}`
|
||||
|
||||
updatedUrls.push(newUrl)
|
||||
} catch (err) {
|
||||
console.error(`Failed to move file "${fileName}" from ${tempBucket} to ${targetBucket}:`, err)
|
||||
if (rawStr.includes(`/${tempBucket}/`)) {
|
||||
updatedUrls.push(rawStr.replace(`/${tempBucket}/`, `/${targetBucket}/`))
|
||||
} else {
|
||||
updatedUrls.push(rawStr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return updatedUrls
|
||||
}
|
||||
|
||||
const getImage = async (bucketName, fileName) => {
|
||||
|
||||
Reference in New Issue
Block a user