Tech-Pangolin / latertots

https://latertots.vercel.app
0 stars 0 forks source link

Feat: Create automation for resetting db with dummy data for dev #10

Open elersong opened 3 months ago

elersong commented 3 months ago
  1. Use Faker to generate new data each time the automation is run.
  2. Use multithreading or Promise.all to leverage existing registration workflow and speed up reset process.
  3. Make sure progress bar is visible in server side console.
  4. Setup script in package.json
elersong commented 3 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();