Skip to content

Helper Function

Firebase Helpers Documentation

Overview

This module provides utility functions for interacting with Firebase services, specifically Firestore and Firebase Storage. It includes functions for converting strings to camel case and uploading files to Firebase Storage while updating Firestore with the file URLs.

Key Features

  1. String Conversion: Converts strings to camel case.
  2. File Upload: Uploads files to Firebase Storage and updates Firestore with the file URLs.

Dependencies

  • Firebase: For Firestore and Storage services.
  • Sonner: For displaying toast notifications.

toCamelCase Function

Converts a string to camel case format.

export function toCamelCase(str: string) {
return str
.replace(/(?:^\w|[A-Z]|\b\w)/g, (word, index) =>
index === 0 ? word.toLowerCase() : word.toUpperCase()
)
.replace(/\s+/g, "");
}

uploadFilesToFireBase Function

Uploads files to Firebase Storage and updates the Firestore document with the download URLs.

Parameters
  • files: An array of File objects to be uploaded.
  • userId: The ID of the user uploading the files.
  • folderName: The name of the folder where files will be stored.
export const uploadFilesToFireBase = async (
files: File[],
userId: string,
folderName: string
) => {
const folderKey = toCamelCase(folderName);
const docRef = doc(db, "supplierSupportingDocs", userId);
for (const file of files) {
const fileRef = ref(storage, `supplierDocs/${userId}/${file.name}`);
try {
const snapshot = await uploadBytes(fileRef, file);
const downloadURL = await getDownloadURL(snapshot.ref);
await setDoc(
docRef,
{ [folderKey]: arrayUnion(downloadURL), userId },
{ merge: true }
);
toast(`Your file ${file.name} has been uploaded`);
return downloadURL;
} catch (error) {
console.error(`Error uploading file ${file.name}:`, error);
throw error;
}
}
};

Upload Files Workflow

  1. Convert Folder Name: Converts the folder name to camel case using toCamelCase.
  2. Reference Document: Creates a reference to the Firestore document for the user’s supporting documents.
  3. Upload File: Uploads each file to Firebase Storage and gets the download URL.
  4. Update Firestore: Updates the Firestore document with the download URL of the uploaded file.
  5. Toast Notification: Displays a toast notification upon successful upload.

Conclusion

This documentation provides an overview of the utility functions for interacting with Firebase services. These functions help in converting strings to camel case and uploading files to Firebase Storage while updating Firestore. For further details, refer to the source code in the project directory.