Skip to content

Instantly share code, notes, and snippets.

@kevinpiac
Last active July 21, 2020 15:05
Show Gist options
  • Save kevinpiac/d7981dc4c69561d1fb6d5325cfb012ee to your computer and use it in GitHub Desktop.
Save kevinpiac/d7981dc4c69561d1fb6d5325cfb012ee to your computer and use it in GitHub Desktop.
Remove all collection's documents and subcollections using firebase-admin
const removeDocumentCollectionsRecursive = async (docRef) => {
const collections = await docRef.listCollections();
return Promise.all(collections.map((colRef) => removeCollectionRecursive(colRef)));
};
const removeDocument = async (docRef) => {
return docRef.delete();
};
const removeCollectionRecursive = async (colRef) => {
const docs = await colRef.listDocuments();
await Promise.all(docs.map((doc) => removeDocumentCollectionsRecursive(doc).then(() => removeDocument(doc))));
}
const removeAllCollectionsRecursive = async (db) => {
const collections = await db.listCollections();
return Promise.all(collections.map((colRef) => removeCollectionRecursive(colRef)));
}
const deleteUser = async (auth, uid) => {
await auth.deleteUser(uid);
return uid;
}
const listAllAuthUsers = (auth) => {
const users = [];
const listAllWithToken = async (nextPageToken) => {
const result = await auth.listUsers(1000, nextPageToken);
result.users.forEach((user) => users.push(user.toJSON()));
if (result.pageToken) {
return listAllWithToken(result.pageToken);
}
return users;
}
return listAllWithToken();
}
const removeAllAuthUsers = async (auth) => {
const users = await listAllAuthUsers(auth);
const res = await auth.deleteUsers(users.map((u) => u.uid));
return {
successCount: res.successCount,
failureCount: res.failureCount,
};
}
module.exports = {
removeCollectionRecursive,
removeAllCollectionsRecursive,
removeDocumentCollectionsRecursive,
removeDocument,
listAllAuthUsers,
removeAllAuthUsers,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment