feat: Add DTO imports processing and update model template for cleaner architecture
This commit is contained in:
@@ -20,7 +20,7 @@ export function generateCode(swaggerFile: string, templatesDir: string): string
|
||||
--global-property models \
|
||||
-t "${templatesDir}" \
|
||||
-o "${tempDir}" \
|
||||
--additional-properties=ngVersion=17.0.0,modelFileSuffix=.dto`;
|
||||
--additional-properties=ngVersion=17.0.0,modelFileSuffix=.dto,modelNameSuffix=Dto`;
|
||||
|
||||
execSync(command, { stdio: 'inherit' });
|
||||
logSuccess('Código generado correctamente');
|
||||
@@ -60,3 +60,63 @@ export function organizeFiles(tempDir: string, outputDir: string): void {
|
||||
|
||||
logSuccess(`${filesMoved} DTOs movidos correctamente`);
|
||||
}
|
||||
|
||||
/** Post-procesa los DTOs generados añadiendo los imports de tipos referenciados. */
|
||||
export function addDtoImports(outputDir: string): void {
|
||||
logStep('Añadiendo imports a los DTOs generados...');
|
||||
|
||||
const dtosDir = path.join(outputDir, 'data/dtos');
|
||||
|
||||
if (!fs.existsSync(dtosDir)) return;
|
||||
|
||||
const files = fs.readdirSync(dtosDir).filter((f) => f.endsWith('.dto.ts'));
|
||||
|
||||
// Build a map of DTO classname → file base name (without .ts)
|
||||
const dtoMap: Record<string, string> = {};
|
||||
files.forEach((file) => {
|
||||
const content = fs.readFileSync(path.join(dtosDir, file), 'utf8');
|
||||
const match = content.match(/export interface (\w+)/);
|
||||
if (match) {
|
||||
dtoMap[match[1]] = file.replace('.ts', '');
|
||||
}
|
||||
});
|
||||
|
||||
let filesProcessed = 0;
|
||||
|
||||
files.forEach((file) => {
|
||||
const filePath = path.join(dtosDir, file);
|
||||
let content = fs.readFileSync(filePath, 'utf8');
|
||||
|
||||
const selfMatch = content.match(/export interface (\w+)/);
|
||||
const selfName = selfMatch ? selfMatch[1] : '';
|
||||
|
||||
// Find all Dto type references in the file body (excluding the interface name itself)
|
||||
const references = new Set<string>();
|
||||
const typeRegex = /\b(\w+Dto)\b/g;
|
||||
let match;
|
||||
while ((match = typeRegex.exec(content)) !== null) {
|
||||
if (match[1] !== selfName) {
|
||||
references.add(match[1]);
|
||||
}
|
||||
}
|
||||
|
||||
if (references.size === 0) return;
|
||||
|
||||
// Build import lines for each referenced type that exists in the dtoMap
|
||||
const imports: string[] = [];
|
||||
references.forEach((ref) => {
|
||||
if (dtoMap[ref]) {
|
||||
imports.push(`import { ${ref} } from './${dtoMap[ref]}';`);
|
||||
}
|
||||
});
|
||||
|
||||
if (imports.length > 0) {
|
||||
content = imports.join('\n') + '\n' + content;
|
||||
fs.writeFileSync(filePath, content);
|
||||
filesProcessed++;
|
||||
logInfo(` Imports añadidos a ${file}`);
|
||||
}
|
||||
});
|
||||
|
||||
logSuccess(`Imports añadidos a ${filesProcessed} DTOs`);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user