All files / src/database/seeds seed-cleanup.service.ts

0% Statements 0/15
0% Branches 0/9
0% Functions 0/2
0% Lines 0/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36                                                                       
import { Injectable, Logger } from '@nestjs/common';
import { Connection } from 'mongoose';
import { InjectConnection } from '@nestjs/mongoose';
 
@Injectable()
export class SeedCleanupService {
  private readonly logger = new Logger(SeedCleanupService.name);
 
  constructor(@InjectConnection() private readonly connection: Connection) {}
 
  async clearDatabase(tenantPrefix: string): Promise<void> {
    this.logger.log(
      `Safely resetting database records matching prefix '${tenantPrefix}'...`,
    );
 
    const collections = this.connection.collections;
    for (const key of Object.keys(collections)) {
      const coll = collections[key];
      // Safely delete demo tenant documents while preserving platform/system definitions
      if (
        coll.name.startsWith('mdm_') ||
        coll.name.startsWith('hr_') ||
        coll.name.startsWith('crm_')
      ) {
        await coll.deleteMany({
          $or: [
            { tenantId: { $exists: true } },
            { recordCode: new RegExp(`^${tenantPrefix}`, 'i') },
          ],
        });
      }
    }
    this.logger.log('Database reset complete.');
  }
}