@magnetarjs/plugin-firestore
Version:
Magnetar plugin firestore
43 lines (42 loc) • 2.39 kB
JavaScript
import { logWithFlair } from '@magnetarjs/utils';
import { getFirestoreCollectionPath, getFirestoreDocPath, } from '@magnetarjs/utils-firestore';
import { doc, getDoc, getDocs } from 'firebase/firestore';
import { isString } from 'is-what';
import { docSnapshotToDocMetadata, getQueryInstance } from '../helpers/getFirestore.js';
export function fetchActionFactory(firestorePluginOptions) {
return async function ({ payload, collectionPath, docId, pluginModuleConfig, }) {
const { db, debug } = firestorePluginOptions;
// in case of a doc module
let snapshots;
if (isString(docId)) {
const documentPath = getFirestoreDocPath(collectionPath, docId, pluginModuleConfig, firestorePluginOptions); // prettier-ignore
const query = doc(db, documentPath);
const warnNoResponse = debug
? setTimeout(() => logWithFlair(`no response after 5 seconds on \`await getDocs(query)\``, 'query:', query), 5_000) // prettier-ignore
: undefined;
const docSnapshot = await getDoc(query);
clearTimeout(warnNoResponse);
snapshots = [docSnapshot];
}
// in case of a collection module
else if (!docId) {
const _collectionPath = getFirestoreCollectionPath(collectionPath, pluginModuleConfig, firestorePluginOptions); // prettier-ignore
const query = getQueryInstance(_collectionPath, pluginModuleConfig, db, debug);
const warnNoResponse = debug
? setTimeout(() => logWithFlair(`no response after 5 seconds on \`await getDocs(query)\``, 'query:', query), 5_000) // prettier-ignore
: undefined;
const querySnapshot = await getDocs(query);
clearTimeout(warnNoResponse);
snapshots = querySnapshot.docs;
}
if (!snapshots)
return { docs: [], reachedEnd: true, cursor: undefined };
const { limit } = pluginModuleConfig;
const reachedEnd = docId || limit === undefined ? true : snapshots.length < limit;
/** @see https://firebase.google.com/docs/firestore/query-data/query-cursors */
const cursor = snapshots[snapshots.length - 1];
// map snapshots to DocMetadata type
const docs = snapshots.map(docSnapshotToDocMetadata);
return { docs, reachedEnd, cursor };
};
}