Spaces:
Sleeping
Sleeping
| 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); | |
| } | |
| } | |
| } | |