Skip to content

Commit 1839b1f

Browse files
committed
Fix s3 images uploading
1 parent 747f5ec commit 1839b1f

File tree

3 files changed

+19
-17
lines changed

3 files changed

+19
-17
lines changed

apps/api/src/images/images.service.ts

+13-12
Original file line numberDiff line numberDiff line change
@@ -24,25 +24,26 @@ export class ImagesService {
2424
dto: ImageDto,
2525
): Promise<string | null> {
2626
const documentHasImage = document.imageKey != null;
27+
const newImageReceived = dto.data != null;
2728

28-
if (dto.hasImage && !documentHasImage) {
29-
if (!dto.data) {
30-
throw new BadRequestException(
31-
'Malformed ImageDto, object does not have and image, data property expected',
32-
);
33-
}
34-
return this.uploadBase64(dto.data);
35-
} else if (!dto.hasImage && documentHasImage) {
36-
await this.s3Service.deleteObject(document.imageKey);
37-
return null;
38-
} else if (dto.hasImage && documentHasImage && dto.data) {
29+
const shouldUploadImage = dto.hasImage && newImageReceived;
30+
const shouldDeleteImage = documentHasImage && (shouldUploadImage || !dto.hasImage);
31+
32+
if (shouldDeleteImage) {
3933
await this.s3Service.deleteObject(document.imageKey);
34+
}
35+
if (shouldUploadImage) {
4036
return this.uploadBase64(dto.data);
4137
}
38+
return null;
39+
}
40+
41+
private base64ToBuffer(base64: string) {
42+
return Buffer.from(base64.replace(/^data:image\/\w+;base64,/, ''), 'base64');
4243
}
4344

4445
private async uploadBase64(base64: string) {
45-
const buffer = Buffer.from(base64, 'base64');
46+
const buffer = this.base64ToBuffer(base64);
4647
const key = await this.s3Service.uploadObject(buffer);
4748
return key;
4849
}

apps/api/src/s3/s3.service.ts

+4-3
Original file line numberDiff line numberDiff line change
@@ -16,17 +16,18 @@ export class S3Service {
1616

1717
private readonly logger = new Logger(S3Service.name);
1818

19-
async uploadObject(file: Buffer): Promise<string> {
19+
async uploadObject(buffer: Buffer): Promise<string> {
2020
const key = this.generateFileKey();
21+
2122
const params: PutObjectCommandInput = {
2223
Bucket: AWS_BUCKET_NAME,
23-
Body: file,
24+
Body: buffer,
2425
Key: key,
2526
};
2627

2728
await this.s3.putObject(params);
2829

29-
this.logger.log(`Uploaded S3 object with key: ${key}`);
30+
this.logger.log(`Uploaded S3 object! Key: "${key}"`);
3031
return key;
3132
}
3233

packages/shared-types/src/ImageDto.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { IsBoolean, IsDataURI, IsEmpty, IsOptional } from "class-validator";
1+
import { IsBoolean, IsDataURI, IsEmpty, IsMimeType, IsOptional } from "class-validator";
22

33
export class ImageDto {
44
@IsBoolean()
@@ -10,5 +10,5 @@ export class ImageDto {
1010

1111
@IsOptional()
1212
@IsDataURI()
13-
data?: string;
13+
data?: string
1414
}

0 commit comments

Comments
 (0)