Last active
July 21, 2020 15:05
-
-
Save kevinpiac/d7981dc4c69561d1fb6d5325cfb012ee to your computer and use it in GitHub Desktop.
Remove all collection's documents and subcollections using firebase-admin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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