File size: 1,394 Bytes
ef874e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { Request, Response, NextFunction } from 'express';
import { uploadBase64ToSupabase } from '../utils/supabase';
import { sukses, gagal } from '../utils/response';
import crypto from 'crypto';

export class UploadController {
  static async uploadProdukFoto(req: Request, res: Response, next: NextFunction) {
    try {
      const { images, prefix } = req.body;
      const cleanPrefix = (prefix || 'img').replace(/[^a-zA-Z0-9-_]/g, '').toLowerCase();
      const uploadedUrls: string[] = [];

      for (let i = 0; i < images.length; i++) {
        const imgBase64 = images[i];

        if (imgBase64.startsWith('http')) {
          uploadedUrls.push(imgBase64);
          continue;
        }

        // Generate unique path/filename
        const uniqueId = crypto.randomBytes(4).toString('hex'); // 8 chars
        const timestamp = Math.floor(Date.now() / 1000);
        const fileName = `${cleanPrefix}_${timestamp}_${uniqueId}_${i}.jpg`;
        const filePath = `produk/${fileName}`;

        const url = await uploadBase64ToSupabase('produk', filePath, imgBase64);

        if (url) {
          uploadedUrls.push(url);
        } else {
          return gagal(res, 500, `Gagal mengunggah foto ke-${i + 1} ke Supabase`);
        }
      }

      return sukses(res, { urls: uploadedUrls }, 'Foto berhasil diunggah ke Supabase');
    } catch (error) {
      next(error);
    }
  }
}