feat: add eager mode to persistMultipartImages

This commit is contained in:
Kirill
2026-05-15 19:55:48 +05:00
parent 3e5e495b9f
commit b22c3f312c
2 changed files with 136 additions and 3 deletions
+18 -3
View File
@@ -14,7 +14,7 @@ export function uploadError(message, statusCode = 400) {
return err
}
export async function persistMultipartImages(request, { maxFiles = 10, maxFileBytes, subdir = '' }) {
export async function persistMultipartImages(request, { maxFiles = 10, maxFileBytes, subdir = '', eager = false }) {
if (!request.isMultipart()) {
throw uploadError('Ожидается multipart/form-data')
}
@@ -40,10 +40,25 @@ export async function persistMultipartImages(request, { maxFiles = 10, maxFileBy
throw uploadError('Разрешены только файлы: png, jpg, jpeg, webp')
}
const fileName = `${crypto.randomUUID()}${ext}`
const uuid = crypto.randomUUID()
const fileName = `${uuid}${ext}`
const fullPath = path.join(targetDir, fileName)
await fs.promises.writeFile(fullPath, await part.toBuffer())
urls.push(subdir ? `/uploads/${subdir}/${fileName}` : `/uploads/${fileName}`)
let finalUrl = subdir ? `/uploads/${subdir}/${fileName}` : `/uploads/${fileName}`
if (eager) {
try {
const { generateAllSizes, convertOriginalToWebp } = await import('./image-resize.js')
await generateAllSizes(uuid, subdir, fullPath)
finalUrl = await convertOriginalToWebp(uuid, subdir)
} catch (error) {
await fs.promises.unlink(fullPath).catch(() => {})
throw error
}
}
urls.push(finalUrl)
}
if (urls.length === 0) {