Gathering detailed insights and metrics for @akshay-khapare/rn-multi-firebase-config
Gathering detailed insights and metrics for @akshay-khapare/rn-multi-firebase-config
Gathering detailed insights and metrics for @akshay-khapare/rn-multi-firebase-config
Gathering detailed insights and metrics for @akshay-khapare/rn-multi-firebase-config
npm install @akshay-khapare/rn-multi-firebase-config
Typescript
Module System
Node Version
NPM Version
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
3
5
5
A production-ready utility package for managing multiple Firebase projects within a single React Native application. This package provides optimized hooks and utilities for Firestore operations, authentication, and storage with comprehensive error handling and type safety.
1npm install @akshay-khapare/rn-multi-firebase-config 2# or 3yarn add @akshay-khapare/rn-multi-firebase-config
Make sure you have the following packages installed in your React Native project:
1npm install @react-native-firebase/app @react-native-firebase/firestore @react-native-firebase/auth @react-native-firebase/storage 2# or 3yarn add @react-native-firebase/app @react-native-firebase/firestore @react-native-firebase/auth @react-native-firebase/storage
Compatibility Note: This package is compatible with Firebase React Native SDK versions 21.6.2 and above, including the latest 22.x versions. It will automatically work with the Firebase version installed in your project.
Initialize a single Firebase instance with custom configuration:
1import { 2 initializeFirebase, 3 FirebaseConfig, 4} from "@akshay-khapare/rn-multi-firebase-config"; 5 6const config: FirebaseConfig = { 7 apiKey: "your-api-key", 8 authDomain: "your-auth-domain", 9 projectId: "your-project-id", 10 storageBucket: "your-storage-bucket", 11 messagingSenderId: "your-messaging-sender-id", 12 appId: "your-app-id", 13 // Optional configurations 14 databaseURL: "your-database-url", 15 measurementId: "your-measurement-id", 16}; 17 18// Initialize Firebase with a project name 19await initializeFirebase("my-project", config); 20 21// Configure Firestore settings 22await configureFirestore("my-project");
Initialize multiple Firebase projects simultaneously:
1import { initializeMultipleFirebaseProjects } from "@akshay-khapare/rn-multi-firebase-config"; 2 3const projectConfigs = [ 4 { 5 name: "project1", 6 config: { 7 apiKey: "project1-api-key", 8 // ... other config properties 9 }, 10 }, 11 { 12 name: "project2", 13 config: { 14 apiKey: "project2-api-key", 15 // ... other config properties 16 }, 17 }, 18]; 19 20// Initialize all projects at once 21await initializeMultipleFirebaseProjects(projectConfigs);
Each project will be initialized with its own configuration and Firestore settings.
Example of handling initialization errors in your application:
1async function initializeFirebaseProjects() { 2 try { 3 await initializeMultipleFirebaseProjects([ 4 { 5 name: "production", 6 config: productionConfig, 7 }, 8 { 9 name: "development", 10 config: developmentConfig, 11 }, 12 ]); 13 console.log("Firebase projects initialized successfully"); 14 } catch (error) { 15 // Handle specific error cases 16 if (error.code === "app/duplicate-app") { 17 console.error("Firebase project already exists"); 18 } else if (error.code === "app/invalid-credential") { 19 console.error("Invalid Firebase credentials"); 20 } else { 21 console.error("Firebase initialization failed:", error); 22 } 23 24 // Rethrow or handle error based on your application needs 25 throw error; 26 } 27}
Project Naming:
Configuration Management:
Initialization Timing:
Error Recovery:
initializeFirebase(projectName: string, config: FirebaseConfig): Promise<void>
Initializes a single Firebase project with the provided configuration.
initializeMultipleFirebaseProjects(configs: Array<{name: string, config: FirebaseConfig}>): Promise<void>
Initializes multiple Firebase projects simultaneously.
configureFirestore(projectName?: string): Promise<void>
Configures Firestore settings for the specified project.
auth(projectName?: string): FirebaseAuthTypes.Module
Returns the Firebase Auth instance for the specified project.
firestore(projectName?: string): FirebaseFirestoreTypes.Module
Returns the Firestore instance for the specified project.
storage(projectName?: string): FirebaseStorageTypes.Module
Returns the Firebase Storage instance for the specified project.
useFirestoreGet()
Provides a getData
function for retrieving single documents from Firestore.
Returns: { getData: <T>(params: GetDataParams) => Promise<DocumentResponse<T>> }
useFirestoreSet()
Provides a setData
function for creating or updating documents in Firestore.
Returns: { setData: (params: SetDataParams) => Promise<string> }
useFirestoreUpdate()
Provides an updateData
function for updating existing documents in Firestore.
Returns: { updateData: (params: UpdateDataParams) => Promise<void> }
useFirestoreGetQuery()
Provides a getQuery
function for executing complex Firestore queries.
Returns: { getQuery: <T>(params: QueryParams) => Promise<QueryResult<T>> }
useCollectionListener()
Provides a listenToCollection
function for real-time collection updates.
Returns: { listenToCollection: <T>(params: ListenerParams<T>) => () => void }
useDocumentListener()
Provides a listenToDocument
function for real-time document updates.
Returns: { listenToDocument: <T>(params: ListenerParams<T>) => () => void }
useIsDocumentExist()
Provides an isExist
function for checking document existence.
Returns: { isExist: (params: DocumentExistParams) => Promise<boolean> }
useFirestoreRef()
Provides a getFirestoreReference
function for obtaining Firestore document references.
Returns: { getFirestoreReference: (params: RefParams) => FirebaseFirestoreTypes.DocumentReference }
1interface FirebaseConfig { 2 apiKey: string; 3 authDomain: string; 4 projectId: string; 5 storageBucket: string; 6 messagingSenderId: string; 7 appId: string; 8 databaseURL?: string; 9 measurementId?: string; 10} 11 12interface GetDataParams { 13 collection: string; 14 doc: string; 15 firebaseProjectName?: string; 16} 17 18interface SetDataParams { 19 collection: string; 20 doc: string; 21 data: Record<string, any>; 22 merge?: boolean; 23 addTimestamp?: boolean; 24 firebaseProject?: string; 25} 26 27interface UpdateDataParams { 28 collection: string; 29 doc: string; 30 data: Record<string, any>; 31 addTimestamp?: boolean; 32 firebaseProject?: string; 33} 34 35interface QueryParams { 36 collection: string; 37 where?: Array<[string, FirebaseFirestoreTypes.WhereFilterOp, any]>; 38 orderBy?: Array<[string, 'asc' | 'desc']>; 39 limit?: number; 40 startAfter?: any; 41 firebaseProject?: string; 42} 43 44interface DocumentExistParams { 45 collection: string; 46 doc: string; 47 firebaseProject?: string; 48}
All hooks include comprehensive error handling:
Contributions are welcome! Please feel free to submit a Pull Request.
MIT License - see the LICENSE file for details.
For issues and questions, please use the GitHub issues page.
1const { listenToCollection } = useCollectionListener(); 2 3// Basic collection listening 4const unsubscribe = listenToCollection<UserData>({ 5 collection: "users", 6 onData: (users) => { 7 console.log("Users updated:", users); 8 }, 9 onError: (error) => { 10 console.error("Error listening to users:", error); 11 }, 12}); 13 14// Advanced querying with filters and ordering 15const unsubscribeFiltered = listenToCollection<ProductData>({ 16 collection: "products", 17 firebaseProject: "store", 18 where: [ 19 ["category", "==", "electronics"], 20 ["price", "<=", 1000], 21 ], 22 orderBy: [ 23 ["price", "asc"], 24 ["name", "asc"], 25 ], 26 limit: 10, 27 onData: (products) => { 28 console.log("Filtered products:", products); 29 }, 30}); 31 32// Cleanup when component unmounts 33return () => { 34 unsubscribe(); 35 unsubscribeFiltered(); 36};
1const { listenToDocument } = useDocumentListener(); 2 3// Basic document listening 4const unsubscribe = listenToDocument<UserProfile>({ 5 collection: "users", 6 doc: "user123", 7 onData: (userData) => { 8 if (userData.exists) { 9 console.log("User data:", userData.data); 10 } else { 11 console.log("User document does not exist"); 12 } 13 }, 14}); 15 16// Multi-project document listening 17const unsubscribeMultiProject = listenToDocument<OrderData>({ 18 collection: "orders", 19 doc: "order123", 20 firebaseProject: "secondary", 21 onData: (orderData) => { 22 console.log("Order status:", orderData.data?.status); 23 }, 24 onError: (error) => { 25 console.error("Error listening to order:", error); 26 }, 27}); 28 29// Cleanup 30return () => { 31 unsubscribe(); 32 unsubscribeMultiProject(); 33};
1const { getData } = useFirestoreGet(); 2 3// Basic document retrieval 4const fetchUserData = async () => { 5 const result = await getData<UserProfile>({ 6 collection: "users", 7 doc: "user123", 8 firebaseProjectName: "main", 9 }); 10 11 if (result.exists) { 12 console.log("User data:", result.data); 13 } 14}; 15 16// Type-safe data retrieval 17interface ProductData { 18 name: string; 19 price: number; 20 stock: number; 21} 22 23const fetchProduct = async (productId: string) => { 24 const result = await getData<ProductData>({ 25 collection: "products", 26 doc: productId, 27 }); 28 29 if (result.exists && result.data) { 30 const { name, price, stock } = result.data; 31 console.log(`${name}: $${price} (${stock} in stock)`); 32 } 33};
1const { getQuery } = useFirestoreGetQuery(); 2 3// Basic query with filters 4const fetchActiveUsers = async () => { 5 const users = await getQuery({ 6 collection: "users", 7 where: [ 8 ["status", "==", "active"], 9 ["lastLogin", ">=", new Date(Date.now() - 86400000)], 10 ], 11 orderBy: [["lastLogin", "desc"]], 12 limit: 10, 13 }); 14 console.log("Active users:", users); 15}; 16 17// Pagination with cursors 18const fetchPaginatedProducts = async (lastProduct?: any) => { 19 const products = await getQuery({ 20 collection: "products", 21 orderBy: [["price", "asc"]], 22 startAfter: lastProduct, 23 limit: 20, 24 }); 25 return products; 26}; 27 28// Complex query with multiple conditions 29const searchProducts = async ( 30 category: string, 31 minPrice: number, 32 maxPrice: number 33) => { 34 const products = await getQuery({ 35 collection: "products", 36 where: [ 37 ["category", "==", category], 38 ["price", ">=", minPrice], 39 ["price", "<=", maxPrice], 40 ["inStock", "==", true], 41 ], 42 orderBy: [ 43 ["price", "asc"], 44 ["name", "asc"], 45 ], 46 }); 47 return products; 48};
1const { setData } = useFirestoreSet(); 2 3// Basic document creation 4const createUser = async (userData: UserData) => { 5 const docId = await setData({ 6 collection: "users", 7 doc: "user123", 8 data: userData, 9 addTimestamp: true, 10 }); 11 console.log("Created user:", docId); 12}; 13 14// Document creation with merge 15const updateUserPartial = async ( 16 userId: string, 17 partialData: Partial<UserData> 18) => { 19 await setData({ 20 collection: "users", 21 doc: userId, 22 data: partialData, 23 merge: true, 24 addTimestamp: true, 25 }); 26}; 27 28// Multi-project document creation 29const createOrder = async (orderData: OrderData) => { 30 await setData({ 31 collection: "orders", 32 doc: `order_${Date.now()}`, 33 data: orderData, 34 firebaseProject: "commerce", 35 addTimestamp: true, 36 }); 37};
1const { executeBatch, executeTransaction } = useFirestoreTransaction(); 2 3// Batch operations 4const updateMultipleDocuments = async () => { 5 const operations = [ 6 { 7 type: "update" as const, 8 collection: "products", 9 doc: "prod1", 10 data: { stock: 10 }, 11 addTimestamp: true, 12 }, 13 { 14 type: "set" as const, 15 collection: "inventory", 16 doc: "inv1", 17 data: { lastChecked: new Date() }, 18 merge: true, 19 }, 20 { 21 type: "delete" as const, 22 collection: "archived", 23 doc: "old1", 24 }, 25 ]; 26 27 const docIds = await executeBatch(operations); 28 console.log("Updated documents:", docIds); 29}; 30 31// Complex transaction 32const transferFunds = async ( 33 fromAccount: string, 34 toAccount: string, 35 amount: number 36) => { 37 await executeTransaction(async (transaction, firestore) => { 38 const fromRef = firestore().collection("accounts").doc(fromAccount); 39 const toRef = firestore().collection("accounts").doc(toAccount); 40 41 const fromSnapshot = await transaction.get(fromRef); 42 const toSnapshot = await transaction.get(toRef); 43 44 const newFromBalance = fromSnapshot.data()!.balance - amount; 45 const newToBalance = toSnapshot.data()!.balance + amount; 46 47 transaction.update(fromRef, { balance: newFromBalance }); 48 transaction.update(toRef, { balance: newToBalance }); 49 50 return { fromBalance: newFromBalance, toBalance: newToBalance }; 51 }); 52};
1const { updateData } = useFirestoreUpdate(); 2 3// Basic document update 4const updateUserProfile = async ( 5 userId: string, 6 updates: Partial<UserProfile> 7) => { 8 await updateData({ 9 collection: "users", 10 doc: userId, 11 data: updates, 12 addTimestamp: true, 13 }); 14}; 15 16// Multi-project document update 17const updateOrderStatus = async (orderId: string, status: string) => { 18 await updateData({ 19 collection: "orders", 20 doc: orderId, 21 data: { status, lastUpdated: new Date() }, 22 firebaseProject: "commerce", 23 addTimestamp: true, 24 }); 25}; 26 27// Partial update with specific fields 28const updateProductStock = async (productId: string, stockChange: number) => { 29 await updateData({ 30 collection: "products", 31 doc: productId, 32 data: { 33 stock: stockChange, 34 lastStockUpdate: new Date(), 35 }, 36 }); 37};
1const { isExist } = useIsDocumentExist(); 2 3// Basic existence check 4const checkUserExists = async (userId: string) => { 5 const exists = await isExist({ 6 collection: "users", 7 doc: userId, 8 }); 9 10 if (exists) { 11 console.log("User exists"); 12 } else { 13 console.log("User not found"); 14 } 15}; 16 17// Multi-project existence check 18const verifyOrder = async (orderId: string) => { 19 const orderExists = await isExist({ 20 collection: "orders", 21 doc: orderId, 22 firebaseProject: "commerce", 23 }); 24 25 return orderExists; 26}; 27 28// Conditional operations based on existence 29const createOrUpdateUser = async (userId: string, userData: UserData) => { 30 const exists = await isExist({ 31 collection: "users", 32 doc: userId, 33 }); 34 35 if (exists) { 36 // Update existing user 37 await updateData({ collection: "users", doc: userId, data: userData }); 38 } else { 39 // Create new user 40 await setData({ collection: "users", doc: userId, data: userData }); 41 } 42};
No vulnerabilities found.
No security vulnerabilities found.