UNPKG

template-nestjs-generator

Version:

A custom NestJS CRUD generator

64 lines (55 loc) 1.99 kB
// TemplateManager.ts import * as fs from "fs-extra" import * as path from "path" import * as Handlebars from "handlebars" class TemplateManager { private templatePath: string private templates: Map<string, HandlebarsTemplateDelegate> constructor(templateDir: string) { this.templatePath = templateDir this.templates = new Map() this.loadTemplates() } private loadTemplates() { const baseTemplates = { entity: "/entities/entity.hbs", module: "/module.hbs", service: "/service.hbs", controller: "/controller.hbs", mapper: "/mapper.hbs", repository: "/repository.hbs", dtoTemplate: "/dtos/dto-template.hbs", } // Load base templates Object.entries(baseTemplates).forEach(([key, file]) => { const templateContent = fs.readFileSync( path.join(this.templatePath, file), "utf8" ) this.templates.set(key, Handlebars.compile(templateContent)) }) // Load DTO templates for different actions const actions = ["create", "response", "update", "delete", "search"] actions.forEach((action) => { const dtoTemplatePath = path.join( this.templatePath, "dtos", `${action}.dto.hbs` ) if (fs.existsSync(dtoTemplatePath)) { const templateContent = fs.readFileSync(dtoTemplatePath, "utf8") this.templates.set( `${action}`, Handlebars.compile(templateContent) ) } }) } getTemplate(name: string) { if (!this.templates.has(name)) { throw new Error(`Template not found: ${name}`) } return this.templates.get(name) } } export default TemplateManager