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

26.47% Statements 9/34
0% Branches 0/11
25% Functions 1/4
23.33% Lines 7/30

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 63 64 65 666x 6x 6x 6x       6x 6x     6x                                                                                                            
import { Injectable, Logger } from '@nestjs/common';
import { ContextSnippetsService } from '../context-snippets/context-snippets.service';
import * as path from 'path';
import { glob } from 'glob';
import { ContextSnippet } from '../core-entities';
 
@Injectable()
export class ContextSnippetSeedingService {
  private readonly logger = new Logger(ContextSnippetSeedingService.name);
 
  constructor(
    private readonly contextSnippetsService: ContextSnippetsService,
  ) {}
 
  async seed() {
    const existingSnippets = await this.contextSnippetsService.findAll();
    const existingSnippetsMap = new Map<string, ContextSnippet>();
    existingSnippets.forEach((s) => existingSnippetsMap.set(s.handle, s));
 
    this.logger.log('Syncing context snippets from files...');
    const seedFiles = await glob(
      path.join(__dirname, 'data', 'context-snippets', '*.{ts,js}'),
    );
 
    Iif (seedFiles.length === 0) {
      this.logger.warn('No context snippet seed files found.');
      return;
    }
 
    for (const filePath of seedFiles) {
      try {
        const snippetModule = await import(filePath);
        const { handle, description, template_content } = snippetModule;
        const fileName = path.basename(filePath);
 
        Iif (!handle || !template_content || template_content.length === 0) {
          this.logger.warn(`Skipping malformed seed file: ${fileName}`);
          continue;
        }
 
        const existingSnippet = existingSnippetsMap.get(handle);
 
        if (existingSnippet) {
          await this.contextSnippetsService.update(existingSnippet.id, {
            description: description || '',
            template_content,
          });
          this.logger.log(`Context snippet "${handle}" updated.`);
        } else {
          await this.contextSnippetsService.create({
            handle,
            description: description || '',
            template_content,
          });
          this.logger.log(`Context snippet "${handle}" seeded.`);
        }
      } catch (error) {
        this.logger.error(
          `Failed to seed context snippet from ${filePath}`,
          error.stack,
        );
      }
    }
  }
}