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

27.27% Statements 9/33
0% Branches 0/8
25% Functions 1/4
24.13% Lines 7/29

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 { CustomSnippetsService } from '../custom-snippets/custom-snippets.service';
import * as path from 'path';
import { glob } from 'glob';
import { CustomSnippet } from '../core-entities';
 
@Injectable()
export class CustomSnippetSeedingService {
  private readonly logger = new Logger(CustomSnippetSeedingService.name);
 
  constructor(private readonly customSnippetsService: CustomSnippetsService) {}
 
  async seed() {
    const existingSnippets = await this.customSnippetsService.findAll();
    const existingSnippetsMap = new Map<string, CustomSnippet>();
    existingSnippets.forEach((s) => existingSnippetsMap.set(s.prefix, s));
 
    this.logger.log('Syncing custom snippets from files...');
    const seedFiles = await glob(
      path.join(__dirname, 'data', 'custom-snippets', '*.{ts,js}'),
    );
 
    Iif (seedFiles.length === 0) {
      this.logger.warn('No custom snippet seed files found.');
      return;
    }
 
    for (const filePath of seedFiles) {
      try {
        const snippetModule = await import(filePath);
        const { prefix, description, body } = snippetModule;
        const fileName = path.basename(filePath);
 
        Iif (!prefix || !description || !body || body.length === 0) {
          this.logger.warn(`Skipping malformed seed file: ${fileName}`);
          continue;
        }
 
        const existingSnippet = existingSnippetsMap.get(prefix);
 
        if (existingSnippet) {
          this.logger.log(
            `Snippet with prefix "${prefix}" already exists, skipping.`,
          );
        } else {
          // Snippet does not exist, create it
          await this.customSnippetsService.create({
            prefix,
            description,
            body,
          });
          this.logger.log(`Snippet "${prefix}" seeded.`);
        }
      } catch (error) {
        this.logger.error(
          `Failed to seed custom snippet from ${filePath}`,
          error.stack,
        );
      }
    }
  }
}