From faa4ca2efb5347ca2a403e25b703bacce44b81d4 Mon Sep 17 00:00:00 2001 From: Roberto Cestari Date: Sun, 4 Aug 2024 16:12:41 -0300 Subject: [PATCH] remove baseurl on edits --- src/lib/s3.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/lib/s3.ts b/src/lib/s3.ts index 06fdc71..ac6da56 100644 --- a/src/lib/s3.ts +++ b/src/lib/s3.ts @@ -47,11 +47,16 @@ export class S3 { } async deleteImage(imagePath: string): Promise { + // remove the base url + imagePath = this.removeBaseUrl(imagePath); + const params = { Bucket: process.env.AWS_BUCKET_NAME ?? '', Key: imagePath, }; + // remove the base url + try { await this.client.send(new DeleteObjectCommand(params)); } catch (e: any) { @@ -59,4 +64,14 @@ export class S3 { throw e; } } + + removeBaseUrl(imageUrl: string): string { + try { + new URL(imageUrl); // Check if it's a valid URL + const url = new URL(imageUrl); + return url.pathname.substring(1); // Remove leading '/' from the pathname + } catch (error) { + return imageUrl; // Return the original if not a valid URL + } + } }