Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Firestore Compatibility Utility
- *
- * This module provides a universal interface for working with Firestore across different platforms
- * (web and React Native). It abstracts away the differences between the Firebase Web SDK and
- * React Native Firebase SDK, providing consistent function signatures and behavior.
- *
- * Usage:
- * - Import firestoreDbInstance as firestoreDb
- * - Import firestoreFunctionsCompat as firestoreFunctions
- *
- * This allows for platform-agnostic Firestore operations throughout the application.
- */
- import { Platform } from 'react-native';
- import { db } from '../../config';
- import { useWebSDK, logPlatformDetection } from '@/lib/utils/platform';
- import structuredClone from '@ungap/structured-clone';
- // Environment detection
- const isWebSDKFlag = useWebSDK();
- logPlatformDetection('FirestoreCompat');
- // Define constraint types for React Native Firebase
- interface QueryConstraint {
- type: 'where' | 'orderBy' | 'limit' | 'startAfter' | 'startAt' | 'endBefore' | 'endAt';
- args: any[];
- }
- // Define the Firestore functions interface
- export interface FirestoreFunctions {
- doc: (db: any, path: string, ...segments: string[]) => any;
- setDoc: (ref: any, data: any, options?: any) => Promise<any>;
- getDoc: (ref: any) => Promise<any>;
- collection: (db: any, path: string, ...segments: string[]) => any;
- addDoc: (ref: any, data: any) => Promise<any>;
- serverTimestamp: () => any;
- query: (ref: any, ...queryConstraints: any[]) => any;
- where: (field: string, opStr: string, value: any) => any;
- orderBy: (field: string, direction?: 'asc' | 'desc') => any;
- limit: (limit: number) => any;
- startAfter: (value: any) => any;
- startAt: (value: any) => any;
- endBefore: (value: any) => any;
- endAt: (value: any) => any;
- getDocs: (queryRef: any) => Promise<any>;
- onSnapshot: (ref: any, onNext: (snapshot: any) => void, onError?: (error: Error) => void) => () => void;
- updateDoc: (ref: any, data: any) => Promise<any>;
- arrayUnion: (...values: any[]) => any;
- arrayRemove: (...values: any[]) => any;
- deleteDoc: (ref: any) => Promise<any>;
- // Batch operations
- writeBatch: (db: any) => any;
- batchSetDoc: (batch: any, ref: any, data: any, options?: any) => void;
- batchUpdateDoc: (batch: any, ref: any, data: any) => void;
- batchDeleteDoc: (batch: any, ref: any) => void;
- batchCommit: (batch: any) => Promise<void>;
- }
- // Initialize Firestore instance and functions based on platform
- let firestoreDbInstance: any;
- let firestoreFunctionsCompat: FirestoreFunctions;
- // Add at the top for consistent logging
- const logSnapshot = (...args: any[]) => {
- if (process.env.NODE_ENV !== 'production') {
- // console.log('[FirestoreCompat][Snapshot]', ...args);
- }
- };
- /**
- * Creates a Web SDK compatible DocumentSnapshot wrapper
- * Ensures all methods and properties match the Firebase JS SDK behavior
- */
- const createWebSDKCompatibleSnapshot = (snapshot: any, docRef: any): any => {
- logSnapshot('createWebSDKCompatibleSnapshot: called', { hasSnapshot: !!snapshot, docRef });
- // Handle null or undefined snapshots
- if (!snapshot) {
- // If this error happens:
- // 1. [firestore/permission-denied] likely means firestore.rules permission is not set correctly
- logSnapshot('createWebSDKCompatibleSnapshot: Received null or undefined document snapshot', { docRef });
- console.error('Error: Received null or undefined document snapshot');
- // Return a valid but empty document snapshot that clearly indicates an error occurred
- const emptySnapshot = {
- exists: () => false,
- data: () => null,
- id: docRef?.id || 'unknown-doc-id',
- ref: docRef,
- get: () => undefined,
- // Flags to identify this as a wrapped error snapshot
- _wrapped: true,
- _type: 'document',
- _isError: true,
- _errorType: 'null_snapshot'
- };
- logSnapshot('createWebSDKCompatibleSnapshot: returning empty snapshot', emptySnapshot);
- return emptySnapshot;
- }
- // Handle case when we receive an already wrapped snapshot
- if (snapshot._wrapped && snapshot._type === 'document') {
- logSnapshot('createWebSDKCompatibleSnapshot: already wrapped snapshot', snapshot);
- return snapshot;
- }
- // Determine if the document exists
- let existsValue = false;
- if (typeof snapshot.exists === 'function') {
- existsValue = snapshot.exists();
- } else if (typeof snapshot.exists === 'boolean') {
- existsValue = snapshot.exists;
- } else {
- try {
- const data = typeof snapshot.data === 'function' ? snapshot.data() : null;
- existsValue = !!data;
- } catch (error) {
- existsValue = false;
- logSnapshot('createWebSDKCompatibleSnapshot: error checking existence', error);
- }
- }
- // Build the snapshot data once to avoid repeated calls
- let snapshotData = null;
- try {
- snapshotData = typeof snapshot.data === 'function' ? snapshot.data() : null;
- } catch (error) {
- snapshotData = null;
- logSnapshot('createWebSDKCompatibleSnapshot: error getting data', error);
- }
- const wrappedSnapshot = {
- data: function() {
- logSnapshot('wrappedSnapshot.data() called', { snapshotData });
- return snapshotData;
- },
- exists: function() {
- logSnapshot('wrappedSnapshot.exists() called', { existsValue });
- return existsValue;
- },
- id: snapshot.id || docRef?.id || '',
- ref: docRef,
- get: function(fieldPath: string) {
- logSnapshot('wrappedSnapshot.get() called', { fieldPath });
- if (!snapshotData) return undefined;
- if (fieldPath.includes('.')) {
- const parts = fieldPath.split('.');
- let value = snapshotData;
- for (const part of parts) {
- if (value === undefined || value === null) return undefined;
- value = value[part];
- }
- logSnapshot('wrappedSnapshot.get() dot notation result', { fieldPath, value });
- return value;
- }
- logSnapshot('wrappedSnapshot.get() direct result', { fieldPath, value: snapshotData[fieldPath] });
- return snapshotData[fieldPath];
- },
- _wrapped: true,
- _type: 'document',
- _originalSnapshot: snapshot
- };
- logSnapshot('createWebSDKCompatibleSnapshot: returning wrappedSnapshot', wrappedSnapshot);
- return wrappedSnapshot;
- };
- /**
- * Creates a Web SDK compatible QuerySnapshot wrapper
- * Ensures all methods and properties match the Firebase JS SDK behavior
- */
- const createWebSDKCompatibleQuerySnapshot = (snapshot: any): any => {
- logSnapshot('createWebSDKCompatibleQuerySnapshot: called', { hasSnapshot: !!snapshot, docsCount: Array.isArray(snapshot?.docs) ? snapshot.docs.length : 0 });
- if (!snapshot) {
- logSnapshot('createWebSDKCompatibleQuerySnapshot: Received null or undefined query snapshot');
- return {
- docs: [],
- empty: true,
- size: 0,
- forEach: (callback: any) => {},
- docChanges: () => [],
- _wrapped: true,
- _type: 'query',
- _isError: true,
- _errorType: 'null_snapshot'
- };
- }
- if (snapshot._wrapped && snapshot._type === 'query') {
- logSnapshot('createWebSDKCompatibleQuerySnapshot: already wrapped snapshot', { docsCount: Array.isArray(snapshot?.docs) ? snapshot.docs.length : 0 });
- return snapshot;
- }
- const docsArray = Array.isArray(snapshot.docs)
- ? snapshot.docs.map((doc: any) => {
- if (doc._wrapped && doc._type === 'document') {
- return doc;
- }
- return createWebSDKCompatibleSnapshot(doc, doc.ref);
- })
- : [];
- const wrappedSnapshot = {
- docs: docsArray,
- empty: docsArray.length === 0,
- size: docsArray.length,
- forEach: function(callback: (doc: any) => void) {
- logSnapshot('wrappedQuerySnapshot.forEach() called', { docsCount: docsArray.length });
- docsArray.forEach((doc: any) => callback(doc));
- },
- docChanges: function() {
- logSnapshot('wrappedQuerySnapshot.docChanges() called', { docsCount: docsArray.length });
- if (typeof snapshot.docChanges === 'function') {
- return snapshot.docChanges().map((change: any) => ({
- ...change,
- doc: change.doc._wrapped
- ? change.doc
- : createWebSDKCompatibleSnapshot(change.doc, change.doc.ref)
- }));
- }
- return docsArray.map((doc: any, index: number) => ({
- type: 'added',
- doc,
- oldIndex: -1,
- newIndex: index
- }));
- },
- _wrapped: true,
- _type: 'query',
- _originalSnapshot: snapshot
- };
- logSnapshot('createWebSDKCompatibleQuerySnapshot: returning wrappedSnapshot', { docsCount: docsArray.length });
- return wrappedSnapshot;
- };
- /**
- * Creates a special wrapper for document snapshots that need to behave like query snapshots
- * This bridges the gap for code that expects a QuerySnapshot but receives a DocumentSnapshot
- */
- const createDocumentAsQuerySnapshot = (docSnapshot: any): any => {
- logSnapshot('createDocumentAsQuerySnapshot: called', { hasDocSnapshot: !!docSnapshot });
- if (!docSnapshot) {
- logSnapshot('createDocumentAsQuerySnapshot: null input');
- return createWebSDKCompatibleQuerySnapshot(null);
- }
- if (docSnapshot._wrapped && docSnapshot._type === 'query') {
- logSnapshot('createDocumentAsQuerySnapshot: already wrapped query snapshot', docSnapshot);
- return docSnapshot;
- }
- const wrappedDoc = docSnapshot._wrapped && docSnapshot._type === 'document'
- ? docSnapshot
- : createWebSDKCompatibleSnapshot(docSnapshot, docSnapshot.ref);
- const querySnapshot = {
- docs: wrappedDoc.exists() ? [wrappedDoc] : [],
- empty: !wrappedDoc.exists(),
- size: wrappedDoc.exists() ? 1 : 0,
- forEach: function(callback: (doc: any) => void) {
- logSnapshot('syntheticQuerySnapshot.forEach() called', { exists: wrappedDoc.exists() });
- if (wrappedDoc.exists()) {
- callback(wrappedDoc);
- }
- },
- docChanges: function() {
- logSnapshot('syntheticQuerySnapshot.docChanges() called', { exists: wrappedDoc.exists() });
- if (!wrappedDoc.exists()) return [];
- return [{
- type: 'added',
- doc: wrappedDoc,
- oldIndex: -1,
- newIndex: 0
- }];
- },
- _wrapped: true,
- _type: 'query',
- _isSynthetic: true,
- _wrappedDoc: wrappedDoc
- };
- logSnapshot('createDocumentAsQuerySnapshot: returning synthetic querySnapshot', querySnapshot);
- return querySnapshot;
- };
- /**
- * Enhanced wrapper function for onSnapshot that properly handles all reference types
- * and ensures consistent behavior between Web SDK and React Native Firebase
- *
- * @param ref The Firestore reference (document, collection, or query)
- * @param onNext Callback function to be called when the snapshot changes
- * @param onError Optional callback function to be called when an error occurs
- * @returns A function to unsubscribe from the snapshot listener
- */
- const wrappedOnSnapshot = (ref: any, onNext: (snapshot: any) => void, onError?: (error: Error) => void): (() => void) => {
- logSnapshot('wrappedOnSnapshot: called', { hasRef: !!ref });
- if (!ref) {
- logSnapshot('wrappedOnSnapshot: Received null or undefined reference');
- console.error('wrappedOnSnapshot: Received null or undefined reference');
- return () => {};
- }
- // Use detectFirestoreRefType for reference type detection
- const refType = detectFirestoreRefType(ref);
- // Determine path for special case handling
- let refPath = '';
- try {
- refPath = ref.path || '';
- } catch (e) {
- // Path might not be accessible for all reference types
- }
- // Get the appropriate platform-specific onSnapshot implementation
- const platformOnSnapshot = (ref: any, onNext: any, onError?: any) => ref.onSnapshot(onNext, onError);
- // Return the unsubscribe function
- return platformOnSnapshot(ref, (snapshot: any) => {
- logSnapshot('wrappedOnSnapshot: snapshot received', { docsCount: Array.isArray(snapshot?.docs) ? snapshot.docs.length : undefined });
- try {
- if (refType === 'document') {
- logSnapshot('wrappedOnSnapshot: Detected Document Reference');
- const wrappedSnapshot = createWebSDKCompatibleSnapshot(snapshot, ref);
- logSnapshot('wrappedOnSnapshot: calling onNext with wrappedSnapshot', wrappedSnapshot);
- onNext(wrappedSnapshot);
- }
- else if (refType === 'collection' || refType === 'query') {
- logSnapshot('wrappedOnSnapshot: Detected Collection/Query Reference');
- const wrappedSnapshot = createWebSDKCompatibleQuerySnapshot(snapshot);
- onNext(wrappedSnapshot);
- }
- else {
- logSnapshot('wrappedOnSnapshot: Unknown Reference Type');
- if (snapshot && typeof snapshot.docs !== 'undefined') {
- logSnapshot('wrappedOnSnapshot: Fallback as QuerySnapshot', { docsCount: Array.isArray(snapshot?.docs) ? snapshot.docs.length : 0 });
- const wrappedSnapshot = createWebSDKCompatibleQuerySnapshot(snapshot);
- onNext(wrappedSnapshot);
- }
- else if (snapshot && (typeof snapshot.exists === 'function' || typeof snapshot.exists === 'boolean')) {
- logSnapshot('wrappedOnSnapshot: Fallback as DocumentSnapshot');
- const wrappedSnapshot = createWebSDKCompatibleSnapshot(snapshot, ref);
- const callStack = new Error().stack || '';
- if (callStack.includes('forEach')) {
- logSnapshot('wrappedOnSnapshot: callStack includes forEach, using createDocumentAsQuerySnapshot');
- onNext(createDocumentAsQuerySnapshot(wrappedSnapshot));
- } else {
- onNext(wrappedSnapshot);
- }
- }
- else {
- logSnapshot('wrappedOnSnapshot: Last resort, passing through raw snapshot');
- console.warn('wrappedOnSnapshot: Unknown snapshot type, passing through raw snapshot');
- onNext(snapshot);
- }
- }
- } catch (error) {
- console.error('Error in wrappedOnSnapshot:', error);
- }
- }, onError);
- };
- /**
- * Detects the type of Firestore reference: document, collection, query, or unknown.
- * Compatible with both Web SDK and React Native Firebase.
- */
- export function detectFirestoreRefType(ref: any): 'document' | 'collection' | 'query' | 'unknown' {
- // Web SDK: DocumentReference has .id and .parent, but no .where()
- if (ref?.id && ref?.parent && typeof ref?.where !== 'function') {
- return 'document';
- }
- // Web SDK: Query has .where() and .get() but no .id or .parent
- if (typeof ref?.where === 'function' && typeof ref?.get === 'function') {
- return 'query';
- }
- // RNFB (React Native Firebase): detect collection/document based on _parts
- if (Array.isArray(ref?._parts)) {
- const partsLength = ref._parts.length;
- if (partsLength % 2 === 0) {
- return 'document'; // Even number of parts = document (e.g., /col/doc)
- } else {
- return 'collection'; // Odd number of parts = collection (e.g., /col)
- }
- }
- return 'unknown';
- }
- if (isWebSDKFlag) {
- // Web SDK imports
- const {
- doc,
- setDoc,
- getDoc,
- collection,
- addDoc,
- serverTimestamp,
- query,
- where,
- orderBy,
- limit,
- startAfter,
- startAt,
- endBefore,
- endAt,
- getDocs,
- onSnapshot,
- updateDoc,
- arrayUnion,
- arrayRemove,
- deleteDoc,
- writeBatch,
- batchSetDoc,
- batchUpdateDoc,
- batchDeleteDoc,
- batchCommit
- } = require('firebase/firestore');
- firestoreDbInstance = db;
- // Store web Firestore functions for later use
- firestoreFunctionsCompat = {
- doc,
- setDoc,
- getDoc,
- collection,
- addDoc,
- serverTimestamp,
- query,
- where,
- orderBy,
- limit,
- startAfter,
- startAt,
- endBefore,
- endAt,
- getDocs,
- onSnapshot,
- updateDoc,
- arrayUnion,
- arrayRemove,
- deleteDoc,
- writeBatch,
- batchSetDoc,
- batchUpdateDoc,
- batchDeleteDoc,
- batchCommit
- };
- } else {
- // React Native Firebase SDK imports
- const firestoreRNFB = require('@react-native-firebase/firestore').default;
- firestoreDbInstance = db;
- const {
- serverTimestamp,
- } = require('@react-native-firebase/firestore');
- // Helper function to create a constraint object
- const createConstraint = (type: 'where' | 'orderBy' | 'limit' | 'startAfter' | 'startAt' | 'endBefore' | 'endAt', args: any[]): QueryConstraint => {
- return { type, args };
- };
- // Universal collection function for React Native Firebase
- const universalCollection = (db: any, path: string, ...segments: string[]): any => {
- // For React Native Firebase, we ignore the db parameter and use the firestore instance
- let ref = firestoreDbInstance;
- // If no segments are provided, just return the collection reference
- if (segments.length === 0) {
- return ref.collection(path);
- }
- // Handle deep nesting paths similar to doc()
- let allSegments = [path, ...segments];
- // Process segments in collection/document pairs
- // For collection, we always need to end with a collection reference
- for (let i = 0; i < allSegments.length; i++) {
- if (i === 0 || i % 2 === 0) {
- // Even indices (0, 2, 4...) are collections
- ref = ref.collection(allSegments[i]);
- } else {
- // Odd indices (1, 3, 5...) are documents
- ref = ref.doc(allSegments[i]);
- }
- }
- return ref;
- };
- // Universal document reference function for React Native Firebase
- const doc = (db: any, path: string, ...segments: string[]): any => {
- // For React Native Firebase, we ignore the db parameter and use the firestore instance
- let ref = firestoreDbInstance;
- // Handle paths like doc(db, 'collection') - should return a document with auto-ID
- if (segments.length === 0) {
- return ref.collection(path).doc();
- }
- // Handle paths like doc(db, 'collection', 'docId')
- if (segments.length === 1) {
- return ref.collection(path).doc(segments[0]);
- }
- // Handle deep nesting paths like doc(db, 'orgs', 'org1', 'projects', 'proj2')
- let allSegments = [path, ...segments];
- // Process segments in collection/document pairs
- for (let i = 0; i < allSegments.length; i += 2) {
- const collectionName = allSegments[i];
- // If we have a collection but no document ID after it, return a reference with auto-ID
- if (i + 1 >= allSegments.length) {
- ref = ref.collection(collectionName).doc();
- break;
- }
- const documentId = allSegments[i + 1];
- ref = ref.collection(collectionName).doc(documentId);
- }
- return ref;
- };
- // Implementation of setDoc for React Native Firebase
- const setDoc = async (docRef: any, data: any, options?: { merge?: boolean }): Promise<void> => {
- return docRef.set(data, options);
- };
- // Implementation of getDoc for React Native Firebase
- const getDoc = async (docRef: any): Promise<any> => {
- try {
- const snapshot = await docRef.get();
- return createWebSDKCompatibleSnapshot(snapshot, docRef);
- } catch (error) {
- console.error('Error in getDoc:', error);
- // Return a non-existent snapshot
- return createWebSDKCompatibleSnapshot(null, docRef);
- }
- };
- // Implementation of addDoc for React Native Firebase
- const addDoc = async (collectionRef: any, data: any): Promise<any> => {
- // React Native Firebase's add method returns a DocumentReference with an auto-generated ID
- const docRef = await collectionRef.add(data);
- // Ensure the returned reference has all expected properties
- if (!docRef.id && docRef.path) {
- // Extract the document ID from the path if it's missing
- const pathSegments = docRef.path.split('/');
- docRef.id = pathSegments[pathSegments.length - 1];
- }
- return docRef;
- };
- // Store RN Firestore functions for later use
- firestoreFunctionsCompat = {
- doc,
- setDoc,
- getDoc,
- collection: universalCollection,
- addDoc,
- serverTimestamp,
- // For React Native Firebase, we need to handle the query constraints differently
- query: (ref: any, ...queryConstraints: any[]) => {
- console.log('[FirestoreCompat][query] Starting query with constraints:', {
- refPath: ref?.path || 'unknown',
- constraintsCount: queryConstraints.length,
- constraints: queryConstraints.map(c => {
- if (typeof c === 'object' && c !== null) {
- return { type: c.type, args: c.args };
- }
- return typeof c;
- })
- });
- let queryRef = ref;
- for (const constraint of queryConstraints) {
- if (!constraint) {
- console.log('[FirestoreCompat][query] Skipping null/undefined constraint');
- continue;
- }
- // New constraint object format (preferred)
- if (typeof constraint === 'object' && 'type' in constraint && Array.isArray(constraint.args)) {
- const { type, args } = constraint;
- console.log(`[FirestoreCompat][query] Processing constraint: ${type}`, { args });
- switch (type) {
- case 'where':
- console.log(`[FirestoreCompat][query] Applying where constraint: ${args[0]} ${args[1]} ${JSON.stringify(args[2])}`);
- queryRef = queryRef.where(...args);
- console.log('[FirestoreCompat][query] Updated query reference:', {
- path: queryRef?.path || 'unknown',
- hasWhere: typeof queryRef?.where === 'function',
- hasOrderBy: typeof queryRef?.orderBy === 'function',
- hasLimit: typeof queryRef?.limit === 'function'
- });
- break;
- case 'orderBy':
- console.log(`[FirestoreCompat][query] Applying orderBy constraint: ${args[0]} ${args[1] || 'asc'}`);
- queryRef = queryRef.orderBy(...args);
- break;
- case 'limit':
- console.log(`[FirestoreCompat][query] Applying limit constraint: ${args[0]}`);
- queryRef = queryRef.limit(...args);
- break;
- case 'startAfter':
- console.log(`[FirestoreCompat][query] Applying startAfter constraint: ${JSON.stringify(args[0])}`);
- queryRef = queryRef.startAfter(...args);
- break;
- case 'startAt':
- console.log(`[FirestoreCompat][query] Applying startAt constraint: ${JSON.stringify(args[0])}`);
- queryRef = queryRef.startAt(...args);
- break;
- case 'endBefore':
- console.log(`[FirestoreCompat][query] Applying endBefore constraint: ${JSON.stringify(args[0])}`);
- queryRef = queryRef.endBefore(...args);
- break;
- case 'endAt':
- console.log(`[FirestoreCompat][query] Applying endAt constraint: ${JSON.stringify(args[0])}`);
- queryRef = queryRef.endAt(...args);
- break;
- default:
- console.warn(`[FirestoreCompat][query] Unsupported query constraint type: ${type}`);
- }
- }
- }
- console.log('[FirestoreCompat][query] Final query reference:', {
- path: queryRef?.path || 'unknown',
- hasWhere: typeof queryRef?.where === 'function',
- hasOrderBy: typeof queryRef?.orderBy === 'function',
- hasLimit: typeof queryRef?.limit === 'function'
- });
- return queryRef;
- },
- // For React Native Firebase, we need to return a constraint object instead of applying it directly
- where: (field: string, opStr: string, value: any) => {
- return createConstraint('where', [field, opStr, value]);
- },
- // Add support for additional query constraints
- orderBy: (field: string, direction: 'asc' | 'desc' = 'asc') => {
- return createConstraint('orderBy', [field, direction]);
- },
- limit: (limit: number) => {
- return createConstraint('limit', [limit]);
- },
- startAfter: (value: any) => {
- return createConstraint('startAfter', [value]);
- },
- startAt: (value: any) => {
- return createConstraint('startAt', [value]);
- },
- endBefore: (value: any) => {
- return createConstraint('endBefore', [value]);
- },
- endAt: (value: any) => {
- return createConstraint('endAt', [value]);
- },
- getDocs: async (queryRef: any) => {
- try {
- console.log('[FirestoreCompat][getDocs] Query reference:', {
- path: queryRef?.path || 'unknown',
- hasWhere: typeof queryRef?.where === 'function',
- hasOrderBy: typeof queryRef?.orderBy === 'function',
- hasLimit: typeof queryRef?.limit === 'function'
- });
- const snapshot = await queryRef.get();
- return createWebSDKCompatibleQuerySnapshot(snapshot);
- } catch (error) {
- // Bug: queryRef.path = unknown
- // Happens when
- console.log('Error in getDocs:', queryRef);
- console.error('Error in getDocs:', error);
- // Return an empty query snapshot
- return createWebSDKCompatibleQuerySnapshot(null);
- }
- },
- onSnapshot: wrappedOnSnapshot,
- updateDoc: (ref: any, data: any) => ref.update(data),
- arrayUnion: (...values: any[]) => {
- return firestoreRNFB.FieldValue.arrayUnion(...values);
- },
- arrayRemove: (...values: any[]) => {
- return firestoreRNFB.FieldValue.arrayRemove(...values);
- },
- deleteDoc: (ref: any) => ref.delete(),
- // Batch operations for React Native Firebase
- writeBatch: (db: any) => {
- // For React Native Firebase, we ignore the db parameter and use the firestore instance
- return firestoreDbInstance.batch();
- },
- batchSetDoc: (batch, ref, data, options) => {
- batch.set(ref, data, options);
- },
- batchUpdateDoc: (batch, ref, data) => {
- batch.update(ref, data);
- },
- batchDeleteDoc: (batch, ref) => {
- batch.delete(ref);
- },
- batchCommit: (batch) => {
- return batch.commit();
- }
- };
- }
- // Export the Firestore instance and functions
- export { firestoreDbInstance, firestoreFunctionsCompat };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement