From a6295586f80f723e569dce58d4ed7c98ff7fdc90 Mon Sep 17 00:00:00 2001 From: Methapon2001 <61303214+Methapon2001@users.noreply.github.com> Date: Wed, 15 Jan 2025 13:28:33 +0700 Subject: [PATCH] feat: handle same name upload --- src/services/minio.ts | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/src/services/minio.ts b/src/services/minio.ts index 28818f6..10a3949 100644 --- a/src/services/minio.ts +++ b/src/services/minio.ts @@ -68,6 +68,24 @@ export async function deleteFolder(path: string) { export async function s3UploadFile(...pathname: string[]) { if (!pathname.length) return; + const list = await s3ListFile(...pathname.slice(0, -1)).catch(exception); + + const fileName = pathname.at(-1) as string; + const dot = fileName.lastIndexOf("."); + const name = dot !== -1 && !fileName.startsWith(".") ? fileName.slice(0, dot) : fileName; + const ext = dot !== -1 && !fileName.startsWith(".") ? fileName.slice(dot) : ""; + + let copy = 0; + let copyFileName = fileName; + + while (list.findIndex((v) => v.fileName === copyFileName) !== -1) { + copyFileName = `${name} (${++copy})${ext}`.trim(); + } + + if (copy > 0) { + await s3UpdateFile(pathname, pathname.slice(0, -1).concat(copyFileName)); + } + const data = { path: pathname.slice(0, -1).join("/"), pathname: pathname.join("/"), @@ -81,10 +99,9 @@ export async function s3UploadFile(...pathname: string[]) { export async function s3UpdateFile(from: string[], to: string[], upload?: boolean) { await minio - .copyObject(MINIO_BUCKET, from.join("/"), [MINIO_BUCKET].concat(to).join("/")) - .then(() => { - minio.removeObject(MINIO_BUCKET, from.join("/")); - }); + .copyObject(MINIO_BUCKET, to.join("/"), [MINIO_BUCKET].concat(from).join("/")) + .catch(exception); + await minio.removeObject(MINIO_BUCKET, from.join("/")).catch(exception); const data = { path: to.slice(0, -1).join("/"),