All files / src/context-snippets context-snippets.service.ts

28.26% Statements 13/46
0% Branches 0/7
11.11% Functions 1/9
25% Lines 11/44

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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 12016x           16x 16x 16x             16x 16x     16x 6x       6x 6x 6x                                                                                                                                                                                          
import {
  BadRequestException,
  Injectable,
  Logger,
  NotFoundException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ContextSnippet } from '../core-entities';
import {
  CreateContextSnippetDto,
  PreviewContextSnippetDto,
  PreviewContextSnippetResponseDto,
  UpdateContextSnippetDto,
} from './dto/context-snippet.dto';
import { ContextGenerationService } from '../context-generation/context-generation.service';
import { CustomVariablesService } from '../custom-variables/custom-variables.service';
 
@Injectable()
export class ContextSnippetsService {
  private readonly logger = new Logger(ContextSnippetsService.name);
 
  constructor(
    @InjectRepository(ContextSnippet)
    private contextSnippetsRepository: Repository<ContextSnippet>,
    private readonly contextGenerationService: ContextGenerationService,
    private readonly customVariablesService: CustomVariablesService,
  ) {}
 
  async create(createDto: CreateContextSnippetDto): Promise<ContextSnippet> {
    const existing = await this.contextSnippetsRepository.findOneBy({
      handle: createDto.handle,
    });
    Iif (existing) {
      throw new BadRequestException(
        `A context snippet with the handle "${createDto.handle}" already exists.`,
      );
    }
    const snippet = this.contextSnippetsRepository.create(createDto);
    return this.contextSnippetsRepository.save(snippet);
  }
 
  async findAll(): Promise<ContextSnippet[]> {
    return this.contextSnippetsRepository.find({ order: { handle: 'ASC' } });
  }
 
  async findOne(id: string): Promise<ContextSnippet> {
    const snippet = await this.contextSnippetsRepository.findOneBy({ id });
    Iif (!snippet) {
      throw new NotFoundException(`ContextSnippet with ID "${id}" not found`);
    }
    return snippet;
  }
 
  async findByHandle(handle: string): Promise<ContextSnippet> {
    const snippet = await this.contextSnippetsRepository.findOneBy({ handle });
    Iif (!snippet) {
      throw new NotFoundException(
        `ContextSnippet with handle "${handle}" not found`,
      );
    }
    return snippet;
  }
 
  async update(
    id: string,
    updateDto: UpdateContextSnippetDto,
  ): Promise<ContextSnippet> {
    const snippet = await this.findOne(id);
 
    Iif (updateDto.handle && updateDto.handle !== snippet.handle) {
      const existing = await this.contextSnippetsRepository.findOneBy({
        handle: updateDto.handle,
      });
      Iif (existing) {
        throw new BadRequestException(
          `A context snippet with the handle "${updateDto.handle}" already exists.`,
        );
      }
    }
 
    this.contextSnippetsRepository.merge(snippet, updateDto);
    return this.contextSnippetsRepository.save(snippet);
  }
 
  async remove(id: string): Promise<void> {
    const snippet = await this.findOne(id);
    await this.contextSnippetsRepository.remove(snippet);
  }
 
  async preview(
    dto: PreviewContextSnippetDto,
  ): Promise<PreviewContextSnippetResponseDto> {
    try {
      const enabledVariables =
        await this.customVariablesService.findAllEnabled();
      const variableMap = enabledVariables.reduce((acc, curr) => {
        acc[curr.key] = curr.value;
        return acc;
      }, {});
 
      const data = {
        VAR: variableMap,
      };
 
      const rendered_text = await this.contextGenerationService.render(
        dto.template_content,
        data,
      );
      return { rendered_text };
    } catch (error) {
      this.logger.error(`Error rendering snippet preview: ${error.message}`);
      return {
        rendered_text: '',
        error: error.message,
      };
    }
  }
}