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 | import { Injectable, NotFoundException, BadRequestException, } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { DocumentTemplate } from './schemas/template.schema'; import * as Handlebars from 'handlebars'; @Injectable() export class TemplateService { constructor( @InjectModel(DocumentTemplate.name) private templateModel: Model<DocumentTemplate>, ) {} async createTemplate( tenantId: string, data: Partial<DocumentTemplate>, ): Promise<DocumentTemplate> { const variables = this.extractVariables(data.content || ''); return this.templateModel.create({ ...data, tenantId, variables, version: 1, }); } async updateTemplate( tenantId: string, templateId: string, data: Partial<DocumentTemplate>, ): Promise<DocumentTemplate> { const template = await this.templateModel.findOne({ _id: templateId, tenantId, }); if (!template) throw new NotFoundException('Template not found'); if (data.content) { data.variables = this.extractVariables(data.content); } data.version = template.version + 1; Object.assign(template, data); return template.save(); } async getTemplate( tenantId: string, templateId: string, ): Promise<DocumentTemplate> { const template = await this.templateModel.findOne({ _id: templateId, tenantId, }); if (!template) throw new NotFoundException('Template not found'); return template; } async listTemplates( tenantId: string, type?: string, ): Promise<DocumentTemplate[]> { const query: any = { tenantId }; if (type) query.type = type; return this.templateModel.find(query).sort({ createdAt: -1 }).exec(); } async renderTemplate( tenantId: string, templateId: string, data: Record<string, any>, ): Promise<string> { const template = await this.getTemplate(tenantId, templateId); try { const compiledTemplate = Handlebars.compile(template.content); return compiledTemplate(data); } catch (error) { throw new BadRequestException( `Failed to render template: ${error.message}`, ); } } private extractVariables(content: string): string[] { const regex = /\{\{([a-zA-Z0-9_]+)\}\}/g; const matches = new Set<string>(); let match; while ((match = regex.exec(content)) !== null) { matches.add(match[1]); } return Array.from(matches); } } |