@magnetarjs/plugin-firestore
Version:
Magnetar plugin firestore
26 lines (25 loc) • 1.47 kB
JavaScript
import { batchSyncFactory, getFirestoreDocPath, } from '@magnetarjs/utils-firestore';
import { collection, doc } from 'firebase/firestore';
import { mapGetOrSet } from 'getorset-anything';
import { isFullString, isNumber } from 'is-what';
import { applySyncBatch, createWriteBatch } from '../helpers/batchHelpers.js';
export function insertActionFactory(batchSyncMap, firestorePluginOptions) {
return async function ({ payload, collectionPath, docId, actionConfig, pluginModuleConfig, }) {
const { db } = firestorePluginOptions;
let _docId = docId;
if (!_docId) {
// we don't have a _docId, so we need to retrieve it from the payload or generate one
_docId =
isFullString(payload['id']) || isNumber(payload['id'])
? String(payload['id'])
: doc(collection(db, 'random')).id;
}
const documentPath = getFirestoreDocPath(collectionPath, _docId, pluginModuleConfig, firestorePluginOptions); // prettier-ignore
const syncDebounceMs = isNumber(actionConfig.syncDebounceMs)
? actionConfig.syncDebounceMs
: pluginModuleConfig.syncDebounceMs;
const batchSync = mapGetOrSet(batchSyncMap, collectionPath, () => batchSyncFactory(firestorePluginOptions, createWriteBatch, applySyncBatch));
const result = await batchSync.insert(documentPath, payload, syncDebounceMs);
return [_docId, result];
};
}