import type { DocumentSnapshot , QueryDocumentSnapshot } from 'firebase/firestore' ; import { doc , getDoc , getDocs } from 'firebase/firestore' ; import { PluginFetchAction , FetchResponse , DocMetadata , PluginFetchActionPayload , } from '@magnetarjs/core' ; import { FirestoreModuleConfig , FirestorePluginOptions } from '../CreatePlugin' ; import { getFirestoreDocPath , getFirestoreCollectionPath } from '../helpers/pathHelpers' ; import { getQueryInstance , docSnapshotToDocMetadata } from '../helpers/queryHelpers' ; export function fetchActionFactory ( firestorePluginOptions ) { return async function ( { payload , collectionPath , docId , pluginModuleConfig , } ) : Promise < FetchResponse > { const { db } = firestorePluginOptions ; let snapshots ; if ( docId ) { const documentPath = getFirestoreDocPath ( collectionPath , docId , pluginModuleConfig , firestorePluginOptions ) ; const docSnapshot = await getDoc ( doc ( db , documentPath ) ) ; snapshots = [ docSnapshot ] ; } else if ( ! docId ) { const _collectionPath = getFirestoreCollectionPath ( collectionPath , pluginModuleConfig , firestorePluginOptions ) ; const queryInstance = getQueryInstance ( _collectionPath , pluginModuleConfig , db ) ; const querySnapshot = await getDocs ( queryInstance ) ; snapshots = querySnapshot . docs ; } if ( ! snapshots ) return { docs : [ ] } ; const docs = snapshots . map ( docSnapshotToDocMetadata ) ; return { docs } ; } ; }