Open elersong opened 5 months ago
Starting point. Will need refactoring and integration
const { db, auth } = require('./firebaseAdmin');
const testData = require('./testData.json');
const clearCollection = async (collectionPath) => {
const collectionRef = db.collection(collectionPath);
const querySnapshot = await collectionRef.get();
const batch = db.batch();
querySnapshot.forEach(doc => {
batch.delete(doc.ref);
});
await batch.commit();
};
const populateCollection = async (collectionPath, data) => {
const batch = db.batch();
data.forEach(item => {
const docRef = db.collection(collectionPath).doc(item.id);
batch.set(docRef, item);
});
await batch.commit();
};
const clearAuthUsers = async () => {
const listUsersResult = await auth.listUsers();
const users = listUsersResult.users;
for (const user of users) {
await auth.deleteUser(user.uid);
}
};
const createAuthUsers = async (users) => {
for (const user of users) {
await auth.createUser({
uid: user.id,
email: user.Email,
password: user.Password,
displayName: user.Name
});
}
};
const resetFirestoreAndAuth = async () => {
try {
console.log('Clearing existing Firestore data...');
await clearCollection('Users');
await clearCollection('Roles');
console.log('Clearing existing Auth users...');
await clearAuthUsers();
console.log('Creating Auth users...');
await createAuthUsers(testData.Users);
console.log('Populating Firestore with test data...');
await populateCollection('Users', testData.Users.map(user => {
const { Password, ...userData } = user; // Remove password from Firestore data
return userData;
}));
await populateCollection('Roles', testData.Roles);
console.log('Firestore and Auth have been reset with test data.');
} catch (error) {
console.error('Error resetting Firestore and Auth:', error);
}
};
resetFirestoreAndAuth();
db.batch()
to speed up process of clearing and populating collections.