Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions backend/testers/cloudinary.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { CloudinaryService } from './cloudinary.service';
// import { CloudinaryProvider } from '../config/cloudinary.config';

@Module({
imports: [ConfigModule],
providers: [CloudinaryService],
exports: [CloudinaryService],
})
export class CloudinaryModule {}
57 changes: 57 additions & 0 deletions backend/testers/cloudinary.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { Injectable, BadRequestException } from '@nestjs/common';
import {
UploadApiErrorResponse,
UploadApiResponse,
v2 as cloudinary,
} from 'cloudinary';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class CloudinaryService {
constructor(private configService: ConfigService) {}

async uploadImage(
file: Express.Multer.File,
folder?: string,
): Promise<UploadApiResponse | UploadApiErrorResponse> {
return new Promise((resolve, reject) => {
const uploadStream = cloudinary.uploader.upload_stream(
{
folder:
folder ||
this.configService.get<string>('CLOUDINARY_FOLDER') ||
'profile-pictures',
resource_type: 'auto',
transformation: [
{ width: 500, height: 500, crop: 'limit' },
{ quality: 'auto:good' },
{ fetch_format: 'auto' },
],
},
(error, result) => {
if (error) return reject(error);
resolve(result);
},
);

uploadStream.end(file.buffer);
});
}

async deleteImage(publicId: string): Promise<any> {
try {
return await cloudinary.uploader.destroy(publicId);
} catch (error) {
throw new BadRequestException('Failed to delete image from Cloudinary');
}
}

extractPublicIdFromUrl(url: string): string {
// Extract public_id from Cloudinary URL
const parts = url.split('/');
const fileWithExtension = parts[parts.length - 1];
const publicId = fileWithExtension.split('.')[0];
const folder = parts[parts.length - 2];
return `${folder}/${publicId}`;
}
}
Loading