|
| 1 | +import { Injectable } from '@nestjs/common'; |
| 2 | +import { initializeApp } from 'firebase/app'; |
| 3 | +import { |
| 4 | + getStorage, |
| 5 | + ref, |
| 6 | + uploadBytes, |
| 7 | + getDownloadURL, |
| 8 | + uploadString, |
| 9 | + UploadMetadata |
| 10 | +} from 'firebase/storage'; |
| 11 | +import { ConfigService } from '@nestjs/config'; |
| 12 | + |
| 13 | +@Injectable() |
| 14 | +export class FirebaseService { |
| 15 | + private app; |
| 16 | + private storage; |
| 17 | + |
| 18 | + constructor(private configService: ConfigService) { |
| 19 | + const firebaseConfig = { |
| 20 | + apiKey: this.configService.get<string>('firebase.apiKey'), |
| 21 | + authDomain: this.configService.get<string>('firebase.authDomain'), |
| 22 | + projectId: this.configService.get<string>('firebase.projectId'), |
| 23 | + storageBucket: this.configService.get<string>('firebase.storageBucket'), |
| 24 | + messagingSenderId: this.configService.get<string>('firebase.messagingSenderId'), |
| 25 | + appId: this.configService.get<string>('firebase.appId'), |
| 26 | + measurementId: this.configService.get<string>('firebase.measurementId') |
| 27 | + }; |
| 28 | + |
| 29 | + this.app = initializeApp(firebaseConfig); |
| 30 | + this.storage = getStorage(this.app); |
| 31 | + } |
| 32 | + |
| 33 | + async uploadFile(file: Express.Multer.File): Promise<{ secure_url: string, originalname: string, mimetype: string }> { |
| 34 | + try { |
| 35 | + // Create a storage reference |
| 36 | + const timestamp = Date.now(); |
| 37 | + const fileName = `${timestamp}_${file.originalname}`; |
| 38 | + const filePath = `mindsmesh-attachments/${fileName}`; |
| 39 | + const storageRef = ref(this.storage, filePath); |
| 40 | + |
| 41 | + // Set metadata |
| 42 | + const metadata: UploadMetadata = { |
| 43 | + contentType: file.mimetype, |
| 44 | + customMetadata: { |
| 45 | + 'originalname': file.originalname, |
| 46 | + }, |
| 47 | + }; |
| 48 | + |
| 49 | + // Upload the file |
| 50 | + const snapshot = await uploadBytes(storageRef, file.buffer, metadata); |
| 51 | + |
| 52 | + // Get the download URL |
| 53 | + const downloadURL = await getDownloadURL(snapshot.ref); |
| 54 | + |
| 55 | + return { |
| 56 | + secure_url: downloadURL, |
| 57 | + originalname: file.originalname, |
| 58 | + mimetype: file.mimetype |
| 59 | + }; |
| 60 | + } catch (error) { |
| 61 | + console.error('Error uploading file to Firebase:', error); |
| 62 | + throw error; |
| 63 | + } |
| 64 | + } |
| 65 | +} |
0 commit comments