Spaces:
Running
Running
| import { Injectable, InternalServerErrorException, Logger } from "@nestjs/common"; | |
| import { UploadApiResponse } from "cloudinary"; | |
| import cloudinary from "./cloudinary.config"; | |
| () | |
| export class CloudinaryService { | |
| private readonly logger = new Logger(CloudinaryService.name); | |
| async uploadImage( | |
| file: Express.Multer.File, | |
| facilityId?: string, | |
| uploadedBy?: string, | |
| ) { | |
| this.logger.log("Attempting to upload image to Cloudinary"); | |
| this.logger.debug("Cloudinary config cloud_name:", cloudinary.config().cloud_name); | |
| this.logger.debug("Cloudinary config api_key:", cloudinary.config().api_key ? "***masked***" : "not set"); | |
| try { | |
| const now = new Date(); | |
| const folder = [ | |
| "maternalert", | |
| "patient-records", | |
| facilityId ?? "unknown", | |
| now.getFullYear(), | |
| String(now.getMonth() + 1).padStart(2, "0"), | |
| ].join("/"); | |
| this.logger.debug("Uploading to folder:", folder); | |
| return await new Promise<UploadApiResponse>((resolve, reject) => { | |
| const stream = cloudinary.uploader.upload_stream( | |
| { | |
| folder, | |
| resource_type: "auto", // Changed to auto to support PDFs too! | |
| use_filename: true, | |
| unique_filename: true, | |
| overwrite: false, | |
| tags: ["patient-record", facilityId ?? "unknown"], | |
| context: { | |
| uploadedBy: uploadedBy ?? "unknown", | |
| facilityId: facilityId ?? "unknown", | |
| }, | |
| }, | |
| (error, result) => { | |
| if (error) { | |
| this.logger.error("Cloudinary upload error:", error); | |
| return reject(error); | |
| } | |
| this.logger.log("Successfully uploaded to Cloudinary:", result?.secure_url); | |
| resolve(result as UploadApiResponse); | |
| }, | |
| ); | |
| stream.end(file.buffer); | |
| }); | |
| } catch (error) { | |
| this.logger.error("Failed to upload image to Cloudinary:", error); | |
| throw new InternalServerErrorException( | |
| `Failed to upload image to Cloudinary: ${(error as Error)?.message || "Unknown error"}`, | |
| ); | |
| } | |
| } | |
| } | |