File size: 2,165 Bytes
55c02e6
27e706d
 
 
 
 
55c02e6
 
27e706d
 
 
 
 
55c02e6
 
 
 
27e706d
 
 
 
 
 
 
 
 
 
 
55c02e6
 
27e706d
 
 
 
55c02e6
27e706d
 
 
 
 
 
 
 
 
 
55c02e6
 
 
 
 
27e706d
 
 
 
 
 
 
55c02e6
27e706d
55c02e6
27e706d
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { Injectable, InternalServerErrorException, Logger } from "@nestjs/common";
import { UploadApiResponse } from "cloudinary";
import cloudinary from "./cloudinary.config";

@Injectable()
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"}`,
      );
    }
  }
}