All files / src/seeding custom-variable-seeding.service.ts

29.03% Statements 9/31
0% Branches 0/6
25% Functions 1/4
25% Lines 7/28

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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 636x 6x 6x 6x     6x 6x     6x                                                                                                        
import { Injectable, Logger } from '@nestjs/common';
import { CustomVariablesService } from '../custom-variables/custom-variables.service';
import * as path from 'path';
import { glob } from 'glob';
 
@Injectable()
export class CustomVariableSeedingService {
  private readonly logger = new Logger(CustomVariableSeedingService.name);
 
  constructor(
    private readonly customVariablesService: CustomVariablesService,
  ) {}
 
  async seed() {
    const existingVariables = await this.customVariablesService.findAll();
    const existingVariableMap = new Map(
      existingVariables.map((v) => [v.key, v]),
    );
 
    this.logger.log('Syncing custom variables from files...');
    const seedFiles = await glob(
      path.join(__dirname, 'data', 'custom-variables', '*.{ts,js}'),
    );
 
    Iif (seedFiles.length === 0) {
      this.logger.log('No custom variable seed files found.');
      return;
    }
 
    for (const filePath of seedFiles) {
      try {
        const variableModule = await import(filePath);
        const { key, value, enabled, is_freq_used } = variableModule;
        const fileName = path.basename(filePath);
 
        Iif (!key || value === undefined) {
          this.logger.warn(`Skipping malformed seed file: ${fileName}`);
          continue;
        }
 
        if (existingVariableMap.has(key)) {
          this.logger.log(
            `Variable with key "${key}" already exists, skipping.`,
          );
        } else {
          await this.customVariablesService.create({
            key,
            value,
            enabled: enabled !== false, // Default to true if not specified
            is_freq_used: is_freq_used === true, // Default to false if not specified
          });
          this.logger.log(`Variable "${key}" seeded.`);
        }
      } catch (error) {
        this.logger.error(
          `Failed to seed custom variable from ${filePath}`,
          error.stack,
        );
      }
    }
  }
}