@puls-atlas/cli
Version:
The Puls Atlas CLI tool for managing Atlas projects
38 lines • 1.77 kB
JavaScript
import { Firestore } from '@google-cloud/firestore';
import { isString } from 'es-toolkit/compat';
const normalizeFirestorePath = firestorePath => {
if (!isString(firestorePath) || firestorePath.trim().length === 0) {
throw new Error('Firestore path is required.');
}
const normalizedPath = firestorePath.trim().replace(/^\/+|\/+$/g, '').replace(/\/{2,}/g, '/');
const segments = normalizedPath.split('/').filter(Boolean);
if (segments.length === 0) {
throw new Error('Firestore path is required.');
}
return segments.join('/');
};
const resolveFirestoreReference = (firestoreClient, firestorePath) => {
const normalizedPath = normalizeFirestorePath(firestorePath);
const segments = normalizedPath.split('/');
if (segments.length % 2 === 0) {
return firestoreClient.doc(normalizedPath);
}
return firestoreClient.collection(normalizedPath);
};
export const deleteFirestorePathRecursively = async (input, dependencies = {}) => {
const projectId = isString(input?.projectId) && input.projectId.trim().length > 0 ? input.projectId.trim() : null;
if (!projectId) {
throw new Error('Firestore recursive delete requires a valid project id.');
}
const createFirestoreClient = dependencies.createFirestoreClient ?? (options => new Firestore(options));
const firestoreClient = dependencies.firestoreClient ?? createFirestoreClient({
projectId
});
const firestoreReference = resolveFirestoreReference(firestoreClient, input?.firestorePath ?? '');
try {
await firestoreClient.recursiveDelete(firestoreReference);
} catch (error) {
throw new Error(`Could not recursively delete Firestore path ${firestoreReference.path} in project ${projectId}. ${error.message}`);
}
};
export default deleteFirestorePathRecursively;