Spaces:
Runtime error

File size: 1,285 Bytes
ad79323
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import crypto from "node:crypto";
import { Client } from "minio";

import {
  MINIO_ACCESS_KEY,
  MINIO_BUCKET_NAME,
  MINIO_ENDPOINT,
  MINIO_PORT,
  MINIO_SECRET_KEY,
  MINIO_USE_SSL,
} from "@/lib/constants";

const globalForMinio = globalThis as unknown as {
  minioClient?: Client;
  minioBucketPromise?: Promise<void>;
};

export const minioClient =
  globalForMinio.minioClient ??
  new Client({
    endPoint: MINIO_ENDPOINT,
    port: MINIO_PORT,
    useSSL: MINIO_USE_SSL,
    accessKey: MINIO_ACCESS_KEY,
    secretKey: MINIO_SECRET_KEY,
  });

if (process.env.NODE_ENV !== "production") {
  globalForMinio.minioClient = minioClient;
}

export async function ensureMinioBucket() {
  if (!globalForMinio.minioBucketPromise) {
    globalForMinio.minioBucketPromise = (async () => {
      const exists = await minioClient.bucketExists(MINIO_BUCKET_NAME);

      if (!exists) {
        await minioClient.makeBucket(MINIO_BUCKET_NAME);
      }
    })();
  }

  return globalForMinio.minioBucketPromise;
}

export function buildCaseFileStorageKey(caseId: string, originalFileName: string) {
  const random = crypto.randomBytes(12).toString("hex");
  const sanitizedName = originalFileName.replace(/[^a-zA-Z0-9._-]/g, "_");

  return `cases/${caseId}/${random}-${sanitizedName}`;
}