File size: 1,608 Bytes
23d4307
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * Firebase Client SDK for Render Server
 * 
 * Uses the same credentials as frontend (NEXT_PUBLIC_* variables).
 * This simplifies deployment since you don't need separate Service Account.
 */

import { initializeApp, getApps } from 'firebase/app';
import { getStorage, ref, uploadBytes, getDownloadURL } from 'firebase/storage';
import fs from 'fs';

const firebaseConfig = {
    apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
    authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
    projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
    storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
    messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
    appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
};

// Check if Firebase is already initialized
const app = getApps().length === 0 ? initializeApp(firebaseConfig) : getApps()[0];
const storage = getStorage(app);

/**
 * Upload a file to Firebase Storage and return the public URL
 */
export async function uploadToFirebase(
    filePath: string,
    destination: string
): Promise<string> {
    console.log(`[Firebase] Uploading ${filePath} to ${destination}`);

    // Read file as buffer
    const fileBuffer = fs.readFileSync(filePath);

    // Create storage reference
    const storageRef = ref(storage, destination);

    // Upload
    await uploadBytes(storageRef, fileBuffer, {
        contentType: 'video/mp4',
    });

    // Get download URL
    const downloadURL = await getDownloadURL(storageRef);
    console.log(`[Firebase] Upload complete: ${downloadURL}`);

    return downloadURL;
}