import { v2 as cloudinary } from 'cloudinary'; import { globalLogger as logger } from './Logger'; import { formatString } from './Strings'; import { ExitCodes } from '../config/Errors'; import { deleteFileThumbnail } from '../middlewares/file.middleware'; import path from 'path'; import { CloudinaryName, CloudinaryKey, CloudSecret, } from '../config/CheckableEnv'; import { StaticRoot } from '../config/Env'; cloudinary.config({ cloud_name: CloudinaryName, api_key: CloudinaryKey, api_secret: CloudSecret, }); /** * @description uploads the zip file to cloudinary * @param path path to the zip file * @returns url of the uploaded file : string */ export async function uploadThumbnailToCloudinary( image: string ): Promise { try { const filePath = path.join(StaticRoot, 'thumbnails', image); const uploadedFile = await cloudinary.uploader.upload(filePath, { folder: 'thumbnails', }); deleteFileThumbnail(image); return uploadedFile.secure_url; } catch (err) { const msg = formatString(ExitCodes.CLOUDINARY_ERROR_GENERIC.message, { error: err, }); logger.error(msg, { code: ExitCodes.CLOUDINARY_ERROR_GENERIC.code, type: ExitCodes.CLOUDINARY_ERROR_GENERIC.type, }); throw new Error('cloudinary error'); } } export const getThumbnailPublicId = (url: string) => { const urlParts = url?.split('/'); const publicId = urlParts[urlParts.length - 2] + '/' + urlParts[urlParts.length - 1]?.split('.')[0]; return publicId; }; export const deleteThumbnailFromCloudinary = async (publicId: string) => { try { await cloudinary.uploader.destroy(publicId); } catch (err) { const msg = formatString(ExitCodes.CLOUDINARY_ERROR_GENERIC.message, { error: err, }); logger.error(msg, { code: ExitCodes.CLOUDINARY_ERROR_GENERIC.code, type: ExitCodes.CLOUDINARY_ERROR_GENERIC.type, }); throw new Error('cloudinary error'); } };