UNPKG

template-nestjs-generator

Version:

A custom NestJS CRUD generator

77 lines (70 loc) 2.88 kB
#!/usr/bin/env node import * as fs from "fs-extra" import * as path from "path" import TemplateManager from "./template-manager" import { getEntityProperties } from "./extract-property" const baseOutputPath = path.join(process.cwd(), "src") export function generateCrud( moduleName: string, templateManager: TemplateManager ) { const outputPath = path.join(process.cwd(), "src", moduleName) fs.ensureDirSync(outputPath) // Generate base files ;["module", "service", "controller", "mapper", "repository"].forEach( (type) => { const template = templateManager.getTemplate(type) const content = template?.({ moduleName }) || "" const filePath = path.join( outputPath, `${moduleName.toLowerCase()}.${type}.ts` ) fs.writeFileSync(filePath, content) console.log(`Generated ${type} at ${filePath}`) } ) const entityTemplate = templateManager.getTemplate("entity") const entityContent = entityTemplate?.({ moduleName }) || "" const entitiesPath = path.join(baseOutputPath, "entities") fs.ensureDirSync(entitiesPath) const entityFilePath = path.join( entitiesPath, `${moduleName.toLowerCase()}.entity.ts` ) // Generate DTOs for each action const dtoPath = path.join(outputPath, "dtos") fs.ensureDirSync(dtoPath) const actions = ["create", "response", "update", "delete", "search"] actions.forEach((action) => { const dtoTemplate = templateManager.getTemplate(`${action}`) const result = dtoTemplate?.({ moduleName }) || "" const filePath = path.join( dtoPath, `${moduleName.toLowerCase()}-${action}.dto.ts` ) fs.writeFileSync(filePath, result) console.log(`Generated ${action}DTO for ${moduleName} at ${filePath}`) }) if (fs.existsSync(entityFilePath)) { console.log(`Entity ${moduleName} already exists at ${entityFilePath}`) const dtoPath = path.join(outputPath, "dtos") fs.ensureDirSync(dtoPath) // Extract properties and generate DTO const properties = getEntityProperties(entityFilePath) const dtoTemplate = templateManager.getTemplate("dtoTemplate") const dtoContent = dtoTemplate?.({ dtoName: `${moduleName}`, properties, }) || "" const dtoFilePath = path.join( dtoPath, `${moduleName.toLowerCase()}-create.dto.ts` ) fs.writeFileSync(dtoFilePath, dtoContent) console.log(`Generated DTO at ${dtoFilePath}`) } else { fs.writeFileSync(entityFilePath, entityContent) console.log(`Generated entity at ${entityFilePath}`) } }