feat: generate upload signed url for oci

This commit is contained in:
Abdalhamid Alhamad
2025-08-03 14:21:14 +03:00
parent fce720237f
commit f65a7d2933
5 changed files with 78 additions and 40 deletions
+8 -1
View File
@@ -1,6 +1,6 @@
import { Injectable, Logger } from '@nestjs/common';
import { FindOptionsWhere } from 'typeorm';
import { UploadDocumentRequestDto } from '../dtos/request';
import { GenerateUploadSignedUrlRequestDto, UploadDocumentRequestDto } from '../dtos/request';
import { Document } from '../entities';
import { DocumentRepository } from '../repositories';
import { OciService } from './oci.service';
@@ -24,4 +24,11 @@ export class DocumentService {
this.logger.log(`finding document with id ${id}`);
return this.documentRepository.findDocumentById(id);
}
generateUploadSignedUrl(body: GenerateUploadSignedUrlRequestDto) {
this.logger.log(
`generating signed URL for document type ${body.documentType} with original file name ${body.originalFileName}`,
);
return this.ociService.generateUploadPreSignedUrl(body);
}
}
+44 -1
View File
@@ -8,7 +8,7 @@ import { CreatePreauthenticatedRequestDetails } from 'oci-objectstorage/lib/mode
import path from 'path';
import { CacheService } from '~/common/modules/cache/services';
import { BUCKETS } from '../constants';
import { UploadDocumentRequestDto } from '../dtos/request';
import { GenerateUploadSignedUrlRequestDto, UploadDocumentRequestDto } from '../dtos/request';
import { UploadResponseDto } from '../dtos/response';
import { Document } from '../entities';
import { generateNewFileName } from '../utils';
@@ -106,4 +106,47 @@ export class OciService {
return document.name;
}
}
async generateUploadPreSignedUrl({
documentType,
originalFileName,
extension,
}: GenerateUploadSignedUrlRequestDto): Promise<UploadResponseDto> {
const bucketName = BUCKETS[documentType];
if (!bucketName) {
this.logger.error('Could not find bucket name for document type', documentType);
throw new BadRequestException('DOCUMENT.TYPE_NOT_SUPPORTED');
}
const objectName = generateNewFileName(originalFileName);
const expiration = moment().add('1', 'hours').toDate();
try {
this.logger.debug(`Generating pre-signed upload URL for object ${objectName} in bucket ${bucketName}`);
const response = await this.ociClient.createPreauthenticatedRequest({
namespaceName: this.namespace,
bucketName,
createPreauthenticatedRequestDetails: {
name: `upload-${objectName}`,
accessType: CreatePreauthenticatedRequestDetails.AccessType.ObjectWrite, // 🔑 for upload
timeExpires: expiration,
objectName: `${objectName}${extension}`, // Ensure the object name includes the extension
},
});
this.logger.log(`Generated upload URL for ${objectName}`);
return plainToInstance(UploadResponseDto, {
name: objectName,
extension,
url: response.preauthenticatedRequest.fullPath,
documentType,
});
} catch (error) {
this.logger.error('Error generating pre-signed upload URL', error);
throw new BadRequestException('UPLOAD.URL_GENERATION_FAILED');
}
}
}