feat: migrate-to-TS #15
7
.prettierrc
Normal file
7
.prettierrc
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"singleQuote": true,
|
||||
"trailingComma": "none",
|
||||
"printWidth": 100,
|
||||
"tabWidth": 2,
|
||||
"semi": true
|
||||
}
|
||||
@@ -112,9 +112,9 @@ import { USER_USE_CASES } from '@/domain/use-cases/user/user.use-cases.contract'
|
||||
})
|
||||
export class UsersComponent {
|
||||
#userUseCases = inject(USER_USE_CASES);
|
||||
|
||||
|
||||
ngOnInit() {
|
||||
this.#userUseCases.getUsers().subscribe(users => {
|
||||
this.#userUseCases.getUsers().subscribe((users) => {
|
||||
console.log(users);
|
||||
});
|
||||
}
|
||||
@@ -126,6 +126,7 @@ export class UsersComponent {
|
||||
### ❌ Error: openapi-generator-cli: command not found
|
||||
|
||||
**Solución:**
|
||||
|
||||
```bash
|
||||
npm install -g @openapitools/openapi-generator-cli
|
||||
```
|
||||
@@ -133,6 +134,7 @@ npm install -g @openapitools/openapi-generator-cli
|
||||
### ❌ Error: Cannot find module 'commander'
|
||||
|
||||
**Solución:**
|
||||
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
@@ -140,6 +142,7 @@ npm install
|
||||
### ❌ Los archivos no se generan
|
||||
|
||||
**Solución:** Verifica que el directorio de salida existe o usa `--dry-run` para ver qué pasaría:
|
||||
|
||||
```bash
|
||||
node generate.js --dry-run
|
||||
```
|
||||
|
||||
@@ -124,6 +124,7 @@ src/app/
|
||||
Los templates están en la carpeta `templates/`. Cada archivo `.mustache` define cómo se genera un tipo de archivo.
|
||||
|
||||
Templates disponibles:
|
||||
|
||||
- `model.mustache` - DTOs
|
||||
- `model-entity.mustache` - Entidades del modelo
|
||||
- `mapper.mustache` - Mappers
|
||||
@@ -208,7 +209,7 @@ import { NodeUseCasesProvider } from '@/di/use-cases/node.use-cases.provider';
|
||||
NodeRepositoryProvider,
|
||||
OrderTypeRepositoryProvider,
|
||||
SupplyModeRepositoryProvider,
|
||||
|
||||
|
||||
// Use Cases
|
||||
NodeUseCasesProvider,
|
||||
OrderTypeUseCasesProvider,
|
||||
@@ -230,9 +231,9 @@ import { NODE_USE_CASES, NodeUseCases } from '@/domain/use-cases/node/node.use-c
|
||||
})
|
||||
export class NodesComponent {
|
||||
#nodeUseCases = inject(NODE_USE_CASES);
|
||||
|
||||
|
||||
loadNodes() {
|
||||
this.#nodeUseCases.getNodes('TI').subscribe(nodes => {
|
||||
this.#nodeUseCases.getNodes('TI').subscribe((nodes) => {
|
||||
console.log(nodes);
|
||||
});
|
||||
}
|
||||
@@ -252,6 +253,7 @@ npm run setup
|
||||
### Error: Archivo swagger.yaml no encontrado
|
||||
|
||||
Asegúrate de especificar la ruta correcta:
|
||||
|
||||
```bash
|
||||
npm run generate -- -i ./ruta/a/tu/swagger.yaml
|
||||
```
|
||||
|
||||
121
dist/generate.js
vendored
121
dist/generate.js
vendored
@@ -11,7 +11,9 @@ const js_yaml_1 = __importDefault(require("js-yaml"));
|
||||
const mustache_1 = __importDefault(require("mustache"));
|
||||
const commander_1 = require("commander");
|
||||
// Desactivar escape HTML para que los literales < y > generen tipos genéricos válidos de TS.
|
||||
mustache_1.default.escape = function (text) { return text; };
|
||||
mustache_1.default.escape = function (text) {
|
||||
return text;
|
||||
};
|
||||
// Colores para console (sin dependencias externas)
|
||||
const colors = {
|
||||
reset: '\x1b[0m',
|
||||
@@ -58,7 +60,7 @@ function checkOpenApiGenerator() {
|
||||
(0, child_process_1.execSync)('openapi-generator-cli version', { stdio: 'ignore' });
|
||||
return true;
|
||||
}
|
||||
catch (error) {
|
||||
catch (_error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -69,7 +71,7 @@ function installOpenApiGenerator() {
|
||||
(0, child_process_1.execSync)('npm install -g @openapitools/openapi-generator-cli', { stdio: 'inherit' });
|
||||
logSuccess('OpenAPI Generator CLI instalado correctamente');
|
||||
}
|
||||
catch (error) {
|
||||
catch (_error) {
|
||||
logError('Error al instalar OpenAPI Generator CLI');
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -86,7 +88,7 @@ function createDirectoryStructure(baseDir) {
|
||||
path_1.default.join(baseDir, 'di/use-cases'),
|
||||
path_1.default.join(baseDir, 'entities/models')
|
||||
];
|
||||
dirs.forEach(dir => {
|
||||
dirs.forEach((dir) => {
|
||||
fs_extra_1.default.ensureDirSync(dir);
|
||||
});
|
||||
logSuccess('Estructura de directorios creada');
|
||||
@@ -97,17 +99,19 @@ function analyzeSwagger(swaggerFile) {
|
||||
try {
|
||||
const fileContent = fs_extra_1.default.readFileSync(swaggerFile, 'utf8');
|
||||
const swagger = js_yaml_1.default.load(fileContent);
|
||||
const tags = swagger.tags || [];
|
||||
const tags = Array.isArray(swagger.tags) ? swagger.tags : [];
|
||||
const paths = swagger.paths || {};
|
||||
logInfo(`Encontrados ${tags.length} tags en el API`);
|
||||
logInfo(`Encontrados ${Object.keys(paths).length} endpoints`);
|
||||
tags.forEach((tag) => {
|
||||
logInfo(` - ${tag.name}: ${tag.description || 'Sin descripción'}`);
|
||||
const t = tag;
|
||||
logInfo(` - ${t.name}: ${t.description || 'Sin descripción'}`);
|
||||
});
|
||||
return { tags, paths, swagger };
|
||||
}
|
||||
catch (error) {
|
||||
logError(`Error al leer el archivo Swagger: ${error.message}`);
|
||||
const err = error;
|
||||
logError(`Error al leer el archivo Swagger: ${err.message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
@@ -131,7 +135,7 @@ function generateCode(swaggerFile, templatesDir) {
|
||||
logSuccess('Código generado correctamente');
|
||||
return tempDir;
|
||||
}
|
||||
catch (error) {
|
||||
catch (_error) {
|
||||
logError('Error al generar código');
|
||||
if (fs_extra_1.default.existsSync(tempDir)) {
|
||||
fs_extra_1.default.removeSync(tempDir);
|
||||
@@ -147,8 +151,8 @@ function organizeFiles(tempDir, outputDir) {
|
||||
let filesMoved = 0;
|
||||
if (fs_extra_1.default.existsSync(sourceDir)) {
|
||||
fs_extra_1.default.ensureDirSync(destDir);
|
||||
const files = fs_extra_1.default.readdirSync(sourceDir).filter(file => file.endsWith('.dto.ts'));
|
||||
files.forEach(file => {
|
||||
const files = fs_extra_1.default.readdirSync(sourceDir).filter((file) => file.endsWith('.dto.ts'));
|
||||
files.forEach((file) => {
|
||||
const sourcePath = path_1.default.join(sourceDir, file);
|
||||
const destPath = path_1.default.join(destDir, file);
|
||||
fs_extra_1.default.copySync(sourcePath, destPath);
|
||||
@@ -160,33 +164,43 @@ function organizeFiles(tempDir, outputDir) {
|
||||
}
|
||||
// Utilidad para mapear tipos OpenAPI elementales a TypeScript
|
||||
function mapSwaggerTypeToTs(type) {
|
||||
if (!type)
|
||||
return 'unknown';
|
||||
const typeMap = {
|
||||
'integer': 'number',
|
||||
'string': 'string',
|
||||
'boolean': 'boolean',
|
||||
'number': 'number',
|
||||
'array': 'Array<any>',
|
||||
'object': 'any'
|
||||
integer: 'number',
|
||||
string: 'string',
|
||||
boolean: 'boolean',
|
||||
number: 'number',
|
||||
array: 'Array<unknown>',
|
||||
object: 'unknown'
|
||||
};
|
||||
return typeMap[type] || 'any';
|
||||
return typeMap[type] || 'unknown';
|
||||
}
|
||||
// Generar Clean Architecture con Mustache
|
||||
function generateCleanArchitecture(analysis, outputDir, templatesDir) {
|
||||
logStep('Generando artefactos de Clean Architecture usando Mustache...');
|
||||
let generatedCount = { models: 0, repositories: 0, mappers: 0, useCases: 0, providers: 0 };
|
||||
const schemas = analysis.swagger.components?.schemas || {};
|
||||
const generatedCount = {
|
||||
models: 0,
|
||||
repositories: 0,
|
||||
mappers: 0,
|
||||
useCases: 0,
|
||||
providers: 0
|
||||
};
|
||||
const schemas = analysis.swagger.components
|
||||
?.schemas || {};
|
||||
// 1. Generar Modelos, Entidades y Mappers a partir de Schemas
|
||||
Object.keys(schemas).forEach(schemaName => {
|
||||
Object.keys(schemas).forEach((schemaName) => {
|
||||
// Sanitizar nombres base para que coincidan con cómo OpenAPI los emite (sin Dto duplicado)
|
||||
const baseName = schemaName.replace(/Dto$/, '');
|
||||
// variables para model
|
||||
const rawProperties = schemas[schemaName].properties || {};
|
||||
const requiredProps = schemas[schemaName].required || [];
|
||||
const varsMap = Object.keys(rawProperties).map(k => {
|
||||
const schemaObj = schemas[schemaName];
|
||||
const rawProperties = schemaObj.properties || {};
|
||||
const requiredProps = schemaObj.required || [];
|
||||
const varsMap = Object.keys(rawProperties).map((k) => {
|
||||
let tsType = mapSwaggerTypeToTs(rawProperties[k].type);
|
||||
if (rawProperties[k].$ref) {
|
||||
// Simple extración del tipo de la ref
|
||||
tsType = rawProperties[k].$ref.split('/').pop() || 'any';
|
||||
tsType = rawProperties[k].$ref.split('/').pop() || 'unknown';
|
||||
}
|
||||
else if (rawProperties[k].type === 'array' && rawProperties[k].items?.$ref) {
|
||||
tsType = `Array<${rawProperties[k].items.$ref.split('/').pop()}>`;
|
||||
@@ -199,15 +213,17 @@ function generateCleanArchitecture(analysis, outputDir, templatesDir) {
|
||||
};
|
||||
});
|
||||
const modelViewData = {
|
||||
models: [{
|
||||
models: [
|
||||
{
|
||||
model: {
|
||||
classname: baseName,
|
||||
classFilename: baseName.toLowerCase(),
|
||||
classVarName: baseName.charAt(0).toLowerCase() + baseName.slice(1),
|
||||
description: schemas[schemaName].description || '',
|
||||
description: schemaObj.description || '',
|
||||
vars: varsMap
|
||||
}
|
||||
}],
|
||||
}
|
||||
],
|
||||
// Para plantillas que esperan allModels o importaciones (mapper)
|
||||
allModels: [{ model: { vars: varsMap } }]
|
||||
};
|
||||
@@ -215,13 +231,15 @@ function generateCleanArchitecture(analysis, outputDir, templatesDir) {
|
||||
const mapperViewData = {
|
||||
...modelViewData,
|
||||
apiInfo: {
|
||||
apis: [{
|
||||
apis: [
|
||||
{
|
||||
operations: {
|
||||
classname: baseName,
|
||||
classFilename: baseName.toLowerCase(),
|
||||
classVarName: baseName.charAt(0).toLowerCase() + baseName.slice(1),
|
||||
classVarName: baseName.charAt(0).toLowerCase() + baseName.slice(1)
|
||||
}
|
||||
}]
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
// Model (Entities)
|
||||
@@ -247,9 +265,9 @@ function generateCleanArchitecture(analysis, outputDir, templatesDir) {
|
||||
// 2. Generar Casos de Uso y Repositorios a partir de Paths/Tags
|
||||
const tagsMap = {};
|
||||
// Agrupar operaciones por Tag
|
||||
Object.keys(analysis.paths).forEach(pathKey => {
|
||||
Object.keys(analysis.paths).forEach((pathKey) => {
|
||||
const pathObj = analysis.paths[pathKey];
|
||||
Object.keys(pathObj).forEach(method => {
|
||||
Object.keys(pathObj).forEach((method) => {
|
||||
const op = pathObj[method];
|
||||
if (op.tags && op.tags.length > 0) {
|
||||
const tag = op.tags[0]; // Usamos el primer tag
|
||||
@@ -258,17 +276,17 @@ function generateCleanArchitecture(analysis, outputDir, templatesDir) {
|
||||
// Parsear parámetros
|
||||
const allParams = (op.parameters || []).map((p) => ({
|
||||
paramName: p.name,
|
||||
dataType: mapSwaggerTypeToTs(p.schema?.type),
|
||||
dataType: mapSwaggerTypeToTs(p.schema?.type || ''),
|
||||
description: p.description || '',
|
||||
required: p.required
|
||||
}));
|
||||
// Añadir body como parámetro si existe
|
||||
if (op.requestBody) {
|
||||
let bodyType = 'any';
|
||||
let bodyType = 'unknown';
|
||||
const content = op.requestBody.content?.['application/json']?.schema;
|
||||
if (content) {
|
||||
if (content.$ref)
|
||||
bodyType = content.$ref.split('/').pop() || 'any';
|
||||
bodyType = content.$ref.split('/').pop() || 'unknown';
|
||||
else if (content.type)
|
||||
bodyType = mapSwaggerTypeToTs(content.type);
|
||||
}
|
||||
@@ -286,11 +304,11 @@ function generateCleanArchitecture(analysis, outputDir, templatesDir) {
|
||||
const responseSchema = op.responses?.['200']?.content?.['application/json']?.schema;
|
||||
if (responseSchema) {
|
||||
if (responseSchema.$ref) {
|
||||
returnType = responseSchema.$ref.split('/').pop() || 'any';
|
||||
returnType = responseSchema.$ref.split('/').pop() || 'unknown';
|
||||
returnBaseType = returnType;
|
||||
}
|
||||
else if (responseSchema.type === 'array' && responseSchema.items?.$ref) {
|
||||
returnBaseType = responseSchema.items.$ref.split('/').pop() || 'any';
|
||||
returnBaseType = responseSchema.items.$ref.split('/').pop() || 'unknown';
|
||||
returnType = `Array<${returnBaseType}>`;
|
||||
isListContainer = true;
|
||||
}
|
||||
@@ -303,7 +321,12 @@ function generateCleanArchitecture(analysis, outputDir, templatesDir) {
|
||||
path: pathKey,
|
||||
allParams: allParams.map((p, i) => ({ ...p, '-last': i === allParams.length - 1 })),
|
||||
hasQueryParams: (op.parameters || []).some((p) => p.in === 'query'),
|
||||
queryParams: (op.parameters || []).filter((p) => p.in === 'query').map((p, i, arr) => ({ paramName: p.name, '-last': i === arr.length - 1 })),
|
||||
queryParams: (op.parameters || [])
|
||||
.filter((p) => p.in === 'query')
|
||||
.map((p, i, arr) => ({
|
||||
paramName: p.name,
|
||||
'-last': i === arr.length - 1
|
||||
})),
|
||||
hasBodyParam: !!op.requestBody,
|
||||
bodyParam: 'body',
|
||||
returnType: returnType !== 'void' ? returnType : false,
|
||||
@@ -315,18 +338,23 @@ function generateCleanArchitecture(analysis, outputDir, templatesDir) {
|
||||
});
|
||||
});
|
||||
// Generar por cada Tag
|
||||
Object.keys(tagsMap).forEach(tag => {
|
||||
Object.keys(tagsMap).forEach((tag) => {
|
||||
// Buscar si ese tag cruza con alguna entidad para importarla
|
||||
const imports = [];
|
||||
Object.keys(schemas).forEach(s => {
|
||||
Object.keys(schemas).forEach((s) => {
|
||||
// Import heurístico burdo
|
||||
if (tagsMap[tag].some((op) => op.returnType === s || op.returnType === `Array<${s}>`)) {
|
||||
imports.push({ classname: s, classFilename: s.toLowerCase(), classVarName: s.charAt(0).toLowerCase() + s.slice(1) });
|
||||
imports.push({
|
||||
classname: s,
|
||||
classFilename: s.toLowerCase(),
|
||||
classVarName: s.charAt(0).toLowerCase() + s.slice(1)
|
||||
});
|
||||
}
|
||||
});
|
||||
const apiViewData = {
|
||||
apiInfo: {
|
||||
apis: [{
|
||||
apis: [
|
||||
{
|
||||
operations: {
|
||||
classname: tag,
|
||||
classFilename: tag.toLowerCase(),
|
||||
@@ -334,7 +362,8 @@ function generateCleanArchitecture(analysis, outputDir, templatesDir) {
|
||||
operation: tagsMap[tag],
|
||||
imports: imports
|
||||
}
|
||||
}]
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
// Use Case Contract
|
||||
@@ -415,7 +444,8 @@ function generateReport(outputDir, analysis) {
|
||||
repositories: fs_extra_1.default.readdirSync(path_1.default.join(outputDir, 'data/repositories')).length,
|
||||
mappers: fs_extra_1.default.readdirSync(path_1.default.join(outputDir, 'data/mappers')).length,
|
||||
useCases: fs_extra_1.default.readdirSync(path_1.default.join(outputDir, 'domain/use-cases')).length,
|
||||
providers: fs_extra_1.default.readdirSync(path_1.default.join(outputDir, 'di/repositories')).length + fs_extra_1.default.readdirSync(path_1.default.join(outputDir, 'di/use-cases')).length
|
||||
providers: fs_extra_1.default.readdirSync(path_1.default.join(outputDir, 'di/repositories')).length +
|
||||
fs_extra_1.default.readdirSync(path_1.default.join(outputDir, 'di/use-cases')).length
|
||||
}
|
||||
};
|
||||
const reportPath = path_1.default.join(process.cwd(), 'generation-report.json');
|
||||
@@ -486,7 +516,8 @@ async function main() {
|
||||
}
|
||||
// Ejecutar
|
||||
main().catch((error) => {
|
||||
logError(`Error fatal: ${error.message}`);
|
||||
const err = error;
|
||||
logError(`Error fatal: ${err.message}`);
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
30
eslint.config.js
Normal file
30
eslint.config.js
Normal file
@@ -0,0 +1,30 @@
|
||||
const eslint = require('@eslint/js');
|
||||
const tseslint = require('typescript-eslint');
|
||||
const eslintPluginPrettierRecommended = require('eslint-plugin-prettier/recommended');
|
||||
|
||||
module.exports = tseslint.config(
|
||||
eslint.configs.recommended,
|
||||
...tseslint.configs.recommendedTypeChecked,
|
||||
eslintPluginPrettierRecommended,
|
||||
{
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.json'],
|
||||
tsconfigRootDir: __dirname
|
||||
}
|
||||
},
|
||||
rules: {
|
||||
'@typescript-eslint/no-explicit-any': 'error',
|
||||
'@typescript-eslint/explicit-function-return-type': 'warn',
|
||||
'@typescript-eslint/no-unsafe-member-access': 'off',
|
||||
'@typescript-eslint/no-unsafe-assignment': 'off',
|
||||
'@typescript-eslint/no-unsafe-call': 'off',
|
||||
'@typescript-eslint/no-unsafe-argument': 'off',
|
||||
'@typescript-eslint/require-await': 'off',
|
||||
'@typescript-eslint/no-unused-vars': ['warn', { 'argsIgnorePattern': '^_', 'varsIgnorePattern': '^_', 'caughtErrorsIgnorePattern': '^_' }]
|
||||
}
|
||||
},
|
||||
{
|
||||
ignores: ['dist/', 'node_modules/', 'eslint.config.js']
|
||||
}
|
||||
);
|
||||
427
generate.ts
427
generate.ts
@@ -8,7 +8,9 @@ import mustache from 'mustache';
|
||||
import { program } from 'commander';
|
||||
|
||||
// Desactivar escape HTML para que los literales < y > generen tipos genéricos válidos de TS.
|
||||
(mustache as any).escape = function(text: string): string { return text; };
|
||||
(mustache as { escape: (text: string) => string }).escape = function (text: string): string {
|
||||
return text;
|
||||
};
|
||||
|
||||
// Colores para console (sin dependencias externas)
|
||||
const colors = {
|
||||
@@ -59,7 +61,7 @@ program
|
||||
.option('--dry-run', 'Simular sin generar archivos')
|
||||
.parse(process.argv);
|
||||
|
||||
interface CliOptions {
|
||||
export interface CliOptions {
|
||||
input: string;
|
||||
output: string;
|
||||
templates: string;
|
||||
@@ -67,14 +69,14 @@ interface CliOptions {
|
||||
dryRun?: boolean;
|
||||
}
|
||||
|
||||
const options = program.opts() as CliOptions;
|
||||
const options = program.opts();
|
||||
|
||||
// Validar que existe openapi-generator-cli
|
||||
function checkOpenApiGenerator(): boolean {
|
||||
try {
|
||||
execSync('openapi-generator-cli version', { stdio: 'ignore' });
|
||||
return true;
|
||||
} catch (error) {
|
||||
} catch (_error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -85,7 +87,7 @@ function installOpenApiGenerator(): void {
|
||||
try {
|
||||
execSync('npm install -g @openapitools/openapi-generator-cli', { stdio: 'inherit' });
|
||||
logSuccess('OpenAPI Generator CLI instalado correctamente');
|
||||
} catch (error) {
|
||||
} catch (_error) {
|
||||
logError('Error al instalar OpenAPI Generator CLI');
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -104,7 +106,7 @@ function createDirectoryStructure(baseDir: string): void {
|
||||
path.join(baseDir, 'entities/models')
|
||||
];
|
||||
|
||||
dirs.forEach(dir => {
|
||||
dirs.forEach((dir) => {
|
||||
fs.ensureDirSync(dir);
|
||||
});
|
||||
|
||||
@@ -112,32 +114,34 @@ function createDirectoryStructure(baseDir: string): void {
|
||||
}
|
||||
|
||||
interface SwaggerAnalysis {
|
||||
tags: any[];
|
||||
paths: Record<string, any>;
|
||||
swagger: any;
|
||||
tags: unknown[];
|
||||
paths: Record<string, unknown>;
|
||||
swagger: unknown;
|
||||
}
|
||||
|
||||
// Analizar el swagger para extraer tags y dominios
|
||||
function analyzeSwagger(swaggerFile: string): SwaggerAnalysis {
|
||||
logStep('Analizando archivo OpenAPI...');
|
||||
|
||||
|
||||
try {
|
||||
const fileContent = fs.readFileSync(swaggerFile, 'utf8');
|
||||
const swagger = yaml.load(fileContent) as any;
|
||||
|
||||
const tags = swagger.tags || [];
|
||||
const paths = swagger.paths || {};
|
||||
|
||||
const swagger = yaml.load(fileContent) as Record<string, unknown>;
|
||||
|
||||
const tags = Array.isArray(swagger.tags) ? swagger.tags : [];
|
||||
const paths = (swagger.paths as Record<string, unknown>) || {};
|
||||
|
||||
logInfo(`Encontrados ${tags.length} tags en el API`);
|
||||
logInfo(`Encontrados ${Object.keys(paths).length} endpoints`);
|
||||
|
||||
tags.forEach((tag: any) => {
|
||||
logInfo(` - ${tag.name}: ${tag.description || 'Sin descripción'}`);
|
||||
|
||||
tags.forEach((tag: unknown) => {
|
||||
const t = tag as { name: string; description?: string };
|
||||
logInfo(` - ${t.name}: ${t.description || 'Sin descripción'}`);
|
||||
});
|
||||
|
||||
|
||||
return { tags, paths, swagger };
|
||||
} catch (error: any) {
|
||||
logError(`Error al leer el archivo Swagger: ${error.message}`);
|
||||
} catch (error: unknown) {
|
||||
const err = error as Error;
|
||||
logError(`Error al leer el archivo Swagger: ${err.message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
@@ -145,14 +149,14 @@ function analyzeSwagger(swaggerFile: string): SwaggerAnalysis {
|
||||
// Generar código con OpenAPI Generator
|
||||
function generateCode(swaggerFile: string, templatesDir: string): string {
|
||||
logStep('Generando código desde OpenAPI...');
|
||||
|
||||
|
||||
const tempDir = path.join(process.cwd(), '.temp-generated');
|
||||
|
||||
|
||||
// Limpiar directorio temporal
|
||||
if (fs.existsSync(tempDir)) {
|
||||
fs.removeSync(tempDir);
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
const command = `openapi-generator-cli generate \
|
||||
-i "${swaggerFile}" \
|
||||
@@ -161,12 +165,12 @@ function generateCode(swaggerFile: string, templatesDir: string): string {
|
||||
-t "${templatesDir}" \
|
||||
-o "${tempDir}" \
|
||||
--additional-properties=ngVersion=17.0.0,modelFileSuffix=.dto`;
|
||||
|
||||
|
||||
execSync(command, { stdio: 'inherit' });
|
||||
logSuccess('Código generado correctamente');
|
||||
|
||||
|
||||
return tempDir;
|
||||
} catch (error) {
|
||||
} catch (_error) {
|
||||
logError('Error al generar código');
|
||||
if (fs.existsSync(tempDir)) {
|
||||
fs.removeSync(tempDir);
|
||||
@@ -178,40 +182,42 @@ function generateCode(swaggerFile: string, templatesDir: string): string {
|
||||
// Organizar archivos según Clean Architecture (DTOs)
|
||||
function organizeFiles(tempDir: string, outputDir: string): void {
|
||||
logStep('Organizando archivos DTO generados...');
|
||||
|
||||
|
||||
const sourceDir = path.join(tempDir, 'model');
|
||||
const destDir = path.join(outputDir, 'data/dtos');
|
||||
let filesMoved = 0;
|
||||
|
||||
|
||||
if (fs.existsSync(sourceDir)) {
|
||||
fs.ensureDirSync(destDir);
|
||||
|
||||
const files = fs.readdirSync(sourceDir).filter(file => file.endsWith('.dto.ts'));
|
||||
|
||||
files.forEach(file => {
|
||||
|
||||
const files = fs.readdirSync(sourceDir).filter((file) => file.endsWith('.dto.ts'));
|
||||
|
||||
files.forEach((file) => {
|
||||
const sourcePath = path.join(sourceDir, file);
|
||||
const destPath = path.join(destDir, file);
|
||||
|
||||
|
||||
fs.copySync(sourcePath, destPath);
|
||||
filesMoved++;
|
||||
logInfo(` ${file} → ${path.relative(process.cwd(), destPath)}`);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
logSuccess(`${filesMoved} DTOs movidos correctamente`);
|
||||
}
|
||||
|
||||
// Utilidad para mapear tipos OpenAPI elementales a TypeScript
|
||||
function mapSwaggerTypeToTs(type: string): string {
|
||||
function mapSwaggerTypeToTs(type?: string): string {
|
||||
if (!type) return 'unknown';
|
||||
|
||||
const typeMap: Record<string, string> = {
|
||||
'integer': 'number',
|
||||
'string': 'string',
|
||||
'boolean': 'boolean',
|
||||
'number': 'number',
|
||||
'array': 'Array<any>',
|
||||
'object': 'any'
|
||||
integer: 'number',
|
||||
string: 'string',
|
||||
boolean: 'boolean',
|
||||
number: 'number',
|
||||
array: 'Array<unknown>',
|
||||
object: 'unknown'
|
||||
};
|
||||
return typeMap[type] || 'any';
|
||||
return typeMap[type] || 'unknown';
|
||||
}
|
||||
|
||||
interface GeneratedCount {
|
||||
@@ -222,32 +228,118 @@ interface GeneratedCount {
|
||||
providers: number;
|
||||
}
|
||||
|
||||
// Generar Clean Architecture con Mustache
|
||||
function generateCleanArchitecture(analysis: SwaggerAnalysis, outputDir: string, templatesDir: string): GeneratedCount {
|
||||
logStep('Generando artefactos de Clean Architecture usando Mustache...');
|
||||
let generatedCount: GeneratedCount = { models: 0, repositories: 0, mappers: 0, useCases: 0, providers: 0 };
|
||||
export interface OpenApiSchema {
|
||||
properties?: Record<
|
||||
string,
|
||||
{
|
||||
type?: string;
|
||||
description?: string;
|
||||
$ref?: string;
|
||||
items?: { $ref?: string };
|
||||
}
|
||||
>;
|
||||
required?: string[];
|
||||
description?: string;
|
||||
}
|
||||
|
||||
export interface OpenApiOperation {
|
||||
tags?: string[];
|
||||
operationId?: string;
|
||||
summary?: string;
|
||||
description?: string;
|
||||
parameters?: Array<{
|
||||
name: string;
|
||||
in: string;
|
||||
required: boolean;
|
||||
description?: string;
|
||||
schema?: { type?: string };
|
||||
}>;
|
||||
requestBody?: {
|
||||
description?: string;
|
||||
content?: Record<
|
||||
string,
|
||||
{
|
||||
schema?: {
|
||||
$ref?: string;
|
||||
type?: string;
|
||||
};
|
||||
}
|
||||
>;
|
||||
};
|
||||
responses?: Record<
|
||||
string,
|
||||
{
|
||||
content?: Record<
|
||||
string,
|
||||
{
|
||||
schema?: {
|
||||
$ref?: string;
|
||||
type?: string;
|
||||
items?: { $ref?: string };
|
||||
};
|
||||
}
|
||||
>;
|
||||
}
|
||||
>;
|
||||
}
|
||||
|
||||
export interface TagOperation {
|
||||
nickname: string;
|
||||
summary: string;
|
||||
notes: string;
|
||||
httpMethod: string;
|
||||
path: string;
|
||||
allParams: unknown[];
|
||||
hasQueryParams: boolean;
|
||||
queryParams: unknown[];
|
||||
hasBodyParam: boolean;
|
||||
bodyParam: string;
|
||||
returnType: string | boolean;
|
||||
returnBaseType: string | boolean;
|
||||
isListContainer: boolean;
|
||||
vendorExtensions: Record<string, unknown>;
|
||||
}
|
||||
|
||||
// Generar Clean Architecture con Mustache
|
||||
function generateCleanArchitecture(
|
||||
analysis: SwaggerAnalysis,
|
||||
outputDir: string,
|
||||
templatesDir: string
|
||||
): GeneratedCount {
|
||||
logStep('Generando artefactos de Clean Architecture usando Mustache...');
|
||||
const generatedCount: GeneratedCount = {
|
||||
models: 0,
|
||||
repositories: 0,
|
||||
mappers: 0,
|
||||
useCases: 0,
|
||||
providers: 0
|
||||
};
|
||||
|
||||
const schemas =
|
||||
(analysis.swagger as { components?: { schemas?: Record<string, unknown> } }).components
|
||||
?.schemas || {};
|
||||
|
||||
const schemas = analysis.swagger.components?.schemas || {};
|
||||
|
||||
// 1. Generar Modelos, Entidades y Mappers a partir de Schemas
|
||||
Object.keys(schemas).forEach(schemaName => {
|
||||
Object.keys(schemas).forEach((schemaName) => {
|
||||
// Sanitizar nombres base para que coincidan con cómo OpenAPI los emite (sin Dto duplicado)
|
||||
const baseName = schemaName.replace(/Dto$/, '');
|
||||
|
||||
|
||||
// variables para model
|
||||
const rawProperties = schemas[schemaName].properties || {};
|
||||
const requiredProps: string[] = schemas[schemaName].required || [];
|
||||
|
||||
const varsMap = Object.keys(rawProperties).map(k => {
|
||||
|
||||
const schemaObj = schemas[schemaName] as OpenApiSchema;
|
||||
const rawProperties = schemaObj.properties || {};
|
||||
const requiredProps: string[] = schemaObj.required || [];
|
||||
|
||||
const varsMap = Object.keys(rawProperties).map((k) => {
|
||||
let tsType = mapSwaggerTypeToTs(rawProperties[k].type);
|
||||
if (rawProperties[k].$ref) {
|
||||
// Simple extración del tipo de la ref
|
||||
tsType = rawProperties[k].$ref.split('/').pop() || 'any';
|
||||
tsType = rawProperties[k].$ref.split('/').pop() || 'unknown';
|
||||
} else if (rawProperties[k].type === 'array' && rawProperties[k].items?.$ref) {
|
||||
tsType = `Array<${rawProperties[k].items.$ref.split('/').pop()}>`;
|
||||
}
|
||||
return {
|
||||
name: k,
|
||||
return {
|
||||
name: k,
|
||||
dataType: tsType,
|
||||
description: rawProperties[k].description || '',
|
||||
required: requiredProps.includes(k)
|
||||
@@ -255,15 +347,17 @@ function generateCleanArchitecture(analysis: SwaggerAnalysis, outputDir: string,
|
||||
});
|
||||
|
||||
const modelViewData = {
|
||||
models: [{
|
||||
model: {
|
||||
classname: baseName,
|
||||
classFilename: baseName.toLowerCase(),
|
||||
classVarName: baseName.charAt(0).toLowerCase() + baseName.slice(1),
|
||||
description: schemas[schemaName].description || '',
|
||||
vars: varsMap
|
||||
models: [
|
||||
{
|
||||
model: {
|
||||
classname: baseName,
|
||||
classFilename: baseName.toLowerCase(),
|
||||
classVarName: baseName.charAt(0).toLowerCase() + baseName.slice(1),
|
||||
description: schemaObj.description || '',
|
||||
vars: varsMap
|
||||
}
|
||||
}
|
||||
}],
|
||||
],
|
||||
// Para plantillas que esperan allModels o importaciones (mapper)
|
||||
allModels: [{ model: { vars: varsMap } }]
|
||||
};
|
||||
@@ -271,14 +365,16 @@ function generateCleanArchitecture(analysis: SwaggerAnalysis, outputDir: string,
|
||||
// Y para mapper.mustache, que además pide apiInfo
|
||||
const mapperViewData = {
|
||||
...modelViewData,
|
||||
apiInfo: {
|
||||
apis: [{
|
||||
operations: {
|
||||
classname: baseName,
|
||||
classFilename: baseName.toLowerCase(),
|
||||
classVarName: baseName.charAt(0).toLowerCase() + baseName.slice(1),
|
||||
}
|
||||
}]
|
||||
apiInfo: {
|
||||
apis: [
|
||||
{
|
||||
operations: {
|
||||
classname: baseName,
|
||||
classFilename: baseName.toLowerCase(),
|
||||
classVarName: baseName.charAt(0).toLowerCase() + baseName.slice(1)
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
@@ -287,7 +383,11 @@ function generateCleanArchitecture(analysis: SwaggerAnalysis, outputDir: string,
|
||||
if (fs.existsSync(modelTemplatePath)) {
|
||||
const template = fs.readFileSync(modelTemplatePath, 'utf8');
|
||||
const output = mustache.render(template, modelViewData);
|
||||
const destPath = path.join(outputDir, 'entities/models', `${baseName.toLowerCase()}.model.ts`);
|
||||
const destPath = path.join(
|
||||
outputDir,
|
||||
'entities/models',
|
||||
`${baseName.toLowerCase()}.model.ts`
|
||||
);
|
||||
fs.writeFileSync(destPath, output);
|
||||
generatedCount.models++;
|
||||
logInfo(` ${baseName.toLowerCase()}.model.ts → ${path.relative(process.cwd(), destPath)}`);
|
||||
@@ -305,32 +405,32 @@ function generateCleanArchitecture(analysis: SwaggerAnalysis, outputDir: string,
|
||||
});
|
||||
|
||||
// 2. Generar Casos de Uso y Repositorios a partir de Paths/Tags
|
||||
const tagsMap: Record<string, any[]> = {};
|
||||
|
||||
const tagsMap: Record<string, TagOperation[]> = {};
|
||||
|
||||
// Agrupar operaciones por Tag
|
||||
Object.keys(analysis.paths).forEach(pathKey => {
|
||||
const pathObj = analysis.paths[pathKey];
|
||||
Object.keys(pathObj).forEach(method => {
|
||||
const op = pathObj[method];
|
||||
Object.keys(analysis.paths).forEach((pathKey) => {
|
||||
const pathObj = analysis.paths[pathKey] as Record<string, unknown>;
|
||||
Object.keys(pathObj).forEach((method) => {
|
||||
const op = pathObj[method] as OpenApiOperation;
|
||||
if (op.tags && op.tags.length > 0) {
|
||||
const tag = op.tags[0]; // Usamos el primer tag
|
||||
if (!tagsMap[tag]) tagsMap[tag] = [];
|
||||
|
||||
|
||||
// Parsear parámetros
|
||||
const allParams = (op.parameters || []).map((p: any) => ({
|
||||
const allParams = (op.parameters || []).map((p) => ({
|
||||
paramName: p.name,
|
||||
dataType: mapSwaggerTypeToTs(p.schema?.type),
|
||||
dataType: mapSwaggerTypeToTs(p.schema?.type || ''),
|
||||
description: p.description || '',
|
||||
required: p.required
|
||||
}));
|
||||
|
||||
|
||||
// Añadir body como parámetro si existe
|
||||
if (op.requestBody) {
|
||||
let bodyType = 'any';
|
||||
let bodyType = 'unknown';
|
||||
const content = op.requestBody.content?.['application/json']?.schema;
|
||||
if (content) {
|
||||
if (content.$ref) bodyType = content.$ref.split('/').pop() || 'any';
|
||||
else if (content.type) bodyType = mapSwaggerTypeToTs(content.type);
|
||||
if (content.$ref) bodyType = content.$ref.split('/').pop() || 'unknown';
|
||||
else if (content.type) bodyType = mapSwaggerTypeToTs(content.type);
|
||||
}
|
||||
allParams.push({
|
||||
paramName: 'body',
|
||||
@@ -339,21 +439,21 @@ function generateCleanArchitecture(analysis: SwaggerAnalysis, outputDir: string,
|
||||
required: true
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// Parsear respuestas
|
||||
let returnType = 'void';
|
||||
let returnBaseType = 'void';
|
||||
let isListContainer = false;
|
||||
const responseSchema = op.responses?.['200']?.content?.['application/json']?.schema;
|
||||
if (responseSchema) {
|
||||
if (responseSchema.$ref) {
|
||||
returnType = responseSchema.$ref.split('/').pop() || 'any';
|
||||
returnBaseType = returnType;
|
||||
} else if (responseSchema.type === 'array' && responseSchema.items?.$ref) {
|
||||
returnBaseType = responseSchema.items.$ref.split('/').pop() || 'any';
|
||||
returnType = `Array<${returnBaseType}>`;
|
||||
isListContainer = true;
|
||||
}
|
||||
if (responseSchema.$ref) {
|
||||
returnType = responseSchema.$ref.split('/').pop() || 'unknown';
|
||||
returnBaseType = returnType;
|
||||
} else if (responseSchema.type === 'array' && responseSchema.items?.$ref) {
|
||||
returnBaseType = responseSchema.items.$ref.split('/').pop() || 'unknown';
|
||||
returnType = `Array<${returnBaseType}>`;
|
||||
isListContainer = true;
|
||||
}
|
||||
}
|
||||
|
||||
tagsMap[tag].push({
|
||||
@@ -362,9 +462,17 @@ function generateCleanArchitecture(analysis: SwaggerAnalysis, outputDir: string,
|
||||
notes: op.description || '',
|
||||
httpMethod: method.toLowerCase(),
|
||||
path: pathKey,
|
||||
allParams: allParams.map((p: any, i: number) => ({ ...p, '-last': i === allParams.length - 1 })),
|
||||
hasQueryParams: (op.parameters || []).some((p: any) => p.in === 'query'),
|
||||
queryParams: (op.parameters || []).filter((p: any) => p.in === 'query').map((p: any, i: number, arr: any[]) => ({ paramName: p.name, '-last': i === arr.length - 1 })),
|
||||
allParams: allParams.map((p, i: number) => ({
|
||||
...p,
|
||||
'-last': i === allParams.length - 1
|
||||
})),
|
||||
hasQueryParams: (op.parameters || []).some((p) => p.in === 'query'),
|
||||
queryParams: (op.parameters || [])
|
||||
.filter((p) => p.in === 'query')
|
||||
.map((p, i: number, arr: unknown[]) => ({
|
||||
paramName: p.name,
|
||||
'-last': i === arr.length - 1
|
||||
})),
|
||||
hasBodyParam: !!op.requestBody,
|
||||
bodyParam: 'body',
|
||||
returnType: returnType !== 'void' ? returnType : false,
|
||||
@@ -377,27 +485,33 @@ function generateCleanArchitecture(analysis: SwaggerAnalysis, outputDir: string,
|
||||
});
|
||||
|
||||
// Generar por cada Tag
|
||||
Object.keys(tagsMap).forEach(tag => {
|
||||
Object.keys(tagsMap).forEach((tag) => {
|
||||
// Buscar si ese tag cruza con alguna entidad para importarla
|
||||
const imports: any[] = [];
|
||||
Object.keys(schemas).forEach(s => {
|
||||
const imports: { classname: string; classFilename: string; classVarName: string }[] = [];
|
||||
Object.keys(schemas).forEach((s) => {
|
||||
// Import heurístico burdo
|
||||
if (tagsMap[tag].some((op: any) => op.returnType === s || op.returnType === `Array<${s}>`)) {
|
||||
imports.push({ classname: s, classFilename: s.toLowerCase(), classVarName: s.charAt(0).toLowerCase() + s.slice(1) });
|
||||
if (tagsMap[tag].some((op) => op.returnType === s || op.returnType === `Array<${s}>`)) {
|
||||
imports.push({
|
||||
classname: s,
|
||||
classFilename: s.toLowerCase(),
|
||||
classVarName: s.charAt(0).toLowerCase() + s.slice(1)
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const apiViewData = {
|
||||
apiInfo: {
|
||||
apis: [{
|
||||
operations: {
|
||||
classname: tag,
|
||||
classFilename: tag.toLowerCase(),
|
||||
constantName: tag.toUpperCase().replace(/[^A-Z0-9]/g, '_'),
|
||||
operation: tagsMap[tag],
|
||||
imports: imports
|
||||
apis: [
|
||||
{
|
||||
operations: {
|
||||
classname: tag,
|
||||
classFilename: tag.toLowerCase(),
|
||||
constantName: tag.toUpperCase().replace(/[^A-Z0-9]/g, '_'),
|
||||
operation: tagsMap[tag],
|
||||
imports: imports
|
||||
}
|
||||
}
|
||||
}]
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
@@ -406,7 +520,11 @@ function generateCleanArchitecture(analysis: SwaggerAnalysis, outputDir: string,
|
||||
if (fs.existsSync(ucContractPath)) {
|
||||
const template = fs.readFileSync(ucContractPath, 'utf8');
|
||||
const output = mustache.render(template, apiViewData);
|
||||
const destPath = path.join(outputDir, 'domain/use-cases', `${tag.toLowerCase()}.use-cases.contract.ts`);
|
||||
const destPath = path.join(
|
||||
outputDir,
|
||||
'domain/use-cases',
|
||||
`${tag.toLowerCase()}.use-cases.contract.ts`
|
||||
);
|
||||
fs.writeFileSync(destPath, output);
|
||||
generatedCount.useCases++;
|
||||
}
|
||||
@@ -416,7 +534,11 @@ function generateCleanArchitecture(analysis: SwaggerAnalysis, outputDir: string,
|
||||
if (fs.existsSync(ucImplPath)) {
|
||||
const template = fs.readFileSync(ucImplPath, 'utf8');
|
||||
const output = mustache.render(template, apiViewData);
|
||||
const destPath = path.join(outputDir, 'domain/use-cases', `${tag.toLowerCase()}.use-cases.impl.ts`);
|
||||
const destPath = path.join(
|
||||
outputDir,
|
||||
'domain/use-cases',
|
||||
`${tag.toLowerCase()}.use-cases.impl.ts`
|
||||
);
|
||||
fs.writeFileSync(destPath, output);
|
||||
generatedCount.useCases++;
|
||||
}
|
||||
@@ -426,7 +548,11 @@ function generateCleanArchitecture(analysis: SwaggerAnalysis, outputDir: string,
|
||||
if (fs.existsSync(repoContractPath)) {
|
||||
const template = fs.readFileSync(repoContractPath, 'utf8');
|
||||
const output = mustache.render(template, apiViewData);
|
||||
const destPath = path.join(outputDir, 'domain/repositories', `${tag.toLowerCase()}.repository.contract.ts`);
|
||||
const destPath = path.join(
|
||||
outputDir,
|
||||
'domain/repositories',
|
||||
`${tag.toLowerCase()}.repository.contract.ts`
|
||||
);
|
||||
fs.writeFileSync(destPath, output);
|
||||
generatedCount.repositories++;
|
||||
}
|
||||
@@ -436,7 +562,11 @@ function generateCleanArchitecture(analysis: SwaggerAnalysis, outputDir: string,
|
||||
if (fs.existsSync(repoImplPath)) {
|
||||
const template = fs.readFileSync(repoImplPath, 'utf8');
|
||||
const output = mustache.render(template, apiViewData);
|
||||
const destPath = path.join(outputDir, 'data/repositories', `${tag.toLowerCase()}.repository.impl.ts`);
|
||||
const destPath = path.join(
|
||||
outputDir,
|
||||
'data/repositories',
|
||||
`${tag.toLowerCase()}.repository.impl.ts`
|
||||
);
|
||||
fs.writeFileSync(destPath, output);
|
||||
generatedCount.repositories++;
|
||||
}
|
||||
@@ -446,7 +576,11 @@ function generateCleanArchitecture(analysis: SwaggerAnalysis, outputDir: string,
|
||||
if (fs.existsSync(ucProviderPath)) {
|
||||
const template = fs.readFileSync(ucProviderPath, 'utf8');
|
||||
const output = mustache.render(template, apiViewData);
|
||||
const destPath = path.join(outputDir, 'di/use-cases', `${tag.toLowerCase()}.use-cases.provider.ts`);
|
||||
const destPath = path.join(
|
||||
outputDir,
|
||||
'di/use-cases',
|
||||
`${tag.toLowerCase()}.use-cases.provider.ts`
|
||||
);
|
||||
fs.writeFileSync(destPath, output);
|
||||
generatedCount.providers++;
|
||||
}
|
||||
@@ -456,13 +590,19 @@ function generateCleanArchitecture(analysis: SwaggerAnalysis, outputDir: string,
|
||||
if (fs.existsSync(repoProviderPath)) {
|
||||
const template = fs.readFileSync(repoProviderPath, 'utf8');
|
||||
const output = mustache.render(template, apiViewData);
|
||||
const destPath = path.join(outputDir, 'di/repositories', `${tag.toLowerCase()}.repository.provider.ts`);
|
||||
const destPath = path.join(
|
||||
outputDir,
|
||||
'di/repositories',
|
||||
`${tag.toLowerCase()}.repository.provider.ts`
|
||||
);
|
||||
fs.writeFileSync(destPath, output);
|
||||
generatedCount.providers++;
|
||||
}
|
||||
});
|
||||
|
||||
logSuccess(`${generatedCount.models} Models, ${generatedCount.repositories} Repos, ${generatedCount.useCases} Use Cases, ${generatedCount.mappers} Mappers, ${generatedCount.providers} Providers generados con Mustache`);
|
||||
logSuccess(
|
||||
`${generatedCount.models} Models, ${generatedCount.repositories} Repos, ${generatedCount.useCases} Use Cases, ${generatedCount.mappers} Mappers, ${generatedCount.providers} Providers generados con Mustache`
|
||||
);
|
||||
return generatedCount;
|
||||
}
|
||||
|
||||
@@ -491,7 +631,7 @@ interface GenerationReport {
|
||||
// Generar reporte
|
||||
function generateReport(outputDir: string, analysis: SwaggerAnalysis): GenerationReport {
|
||||
logStep('Generando reporte de generación...');
|
||||
|
||||
|
||||
const report: GenerationReport = {
|
||||
timestamp: new Date().toISOString(),
|
||||
tags: analysis.tags.length,
|
||||
@@ -502,15 +642,17 @@ function generateReport(outputDir: string, analysis: SwaggerAnalysis): Generatio
|
||||
repositories: fs.readdirSync(path.join(outputDir, 'data/repositories')).length,
|
||||
mappers: fs.readdirSync(path.join(outputDir, 'data/mappers')).length,
|
||||
useCases: fs.readdirSync(path.join(outputDir, 'domain/use-cases')).length,
|
||||
providers: fs.readdirSync(path.join(outputDir, 'di/repositories')).length + fs.readdirSync(path.join(outputDir, 'di/use-cases')).length
|
||||
providers:
|
||||
fs.readdirSync(path.join(outputDir, 'di/repositories')).length +
|
||||
fs.readdirSync(path.join(outputDir, 'di/use-cases')).length
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
const reportPath = path.join(process.cwd(), 'generation-report.json');
|
||||
fs.writeJsonSync(reportPath, report, { spaces: 2 });
|
||||
|
||||
|
||||
logSuccess(`Reporte guardado en: ${reportPath}`);
|
||||
|
||||
|
||||
return report;
|
||||
}
|
||||
|
||||
@@ -520,60 +662,62 @@ async function main(): Promise<void> {
|
||||
log(' OpenAPI Clean Architecture Generator', 'bright');
|
||||
log(' Angular + Clean Architecture Code Generator', 'cyan');
|
||||
console.log('='.repeat(60) + '\n');
|
||||
|
||||
|
||||
// Validar archivo de entrada
|
||||
if (!fs.existsSync(options.input)) {
|
||||
logError(`Archivo no encontrado: ${options.input}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
|
||||
logInfo(`Archivo de entrada: ${options.input}`);
|
||||
logInfo(`Directorio de salida: ${options.output}`);
|
||||
logInfo(`Templates: ${options.templates}`);
|
||||
|
||||
|
||||
if (options.dryRun) {
|
||||
logWarning('Modo DRY RUN - No se generarán archivos');
|
||||
}
|
||||
|
||||
|
||||
// Verificar/Instalar OpenAPI Generator
|
||||
if (!checkOpenApiGenerator()) {
|
||||
logWarning('OpenAPI Generator CLI no encontrado');
|
||||
if (!options.skipInstall) {
|
||||
installOpenApiGenerator();
|
||||
} else {
|
||||
logError('Instala openapi-generator-cli con: npm install -g @openapitools/openapi-generator-cli');
|
||||
logError(
|
||||
'Instala openapi-generator-cli con: npm install -g @openapitools/openapi-generator-cli'
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
} else {
|
||||
logSuccess('OpenAPI Generator CLI encontrado');
|
||||
}
|
||||
|
||||
|
||||
// Analizar Swagger
|
||||
const analysis = analyzeSwagger(options.input);
|
||||
|
||||
|
||||
if (options.dryRun) {
|
||||
logInfo('Finalizando en modo DRY RUN');
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
// Crear estructura de directorios
|
||||
createDirectoryStructure(options.output);
|
||||
|
||||
|
||||
// Generar código
|
||||
const tempDir = generateCode(options.input, options.templates);
|
||||
|
||||
|
||||
// Organizar archivos
|
||||
organizeFiles(tempDir, options.output);
|
||||
|
||||
|
||||
// Crear componentes Clean Architecture con nuestro script de Mustache
|
||||
generateCleanArchitecture(analysis, options.output, options.templates);
|
||||
|
||||
|
||||
// Limpiar
|
||||
cleanup(tempDir);
|
||||
|
||||
|
||||
// Generar reporte
|
||||
const report = generateReport(options.output, analysis);
|
||||
|
||||
|
||||
// Resumen final
|
||||
console.log('\n' + '='.repeat(60));
|
||||
log(' ✨ Generación completada con éxito', 'green');
|
||||
@@ -588,8 +732,9 @@ async function main(): Promise<void> {
|
||||
}
|
||||
|
||||
// Ejecutar
|
||||
main().catch((error: any) => {
|
||||
logError(`Error fatal: ${error.message}`);
|
||||
main().catch((error: unknown) => {
|
||||
const err = error as Error;
|
||||
logError(`Error fatal: ${err.message}`);
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
14
package.json
14
package.json
@@ -11,6 +11,9 @@
|
||||
"prepublishOnly": "npm run build",
|
||||
"generate": "node dist/generate.js",
|
||||
"generate:dev": "ts-node generate.ts",
|
||||
"lint": "eslint 'generate.ts' -f unix",
|
||||
"lint:fix": "eslint 'generate.ts' --fix -f unix",
|
||||
"format": "prettier --write .",
|
||||
"setup": "npm install -g @openapitools/openapi-generator-cli"
|
||||
},
|
||||
"keywords": [
|
||||
@@ -33,11 +36,20 @@
|
||||
"node": ">=14.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@types/fs-extra": "^11.0.4",
|
||||
"@types/js-yaml": "^4.0.9",
|
||||
"@types/mustache": "^4.2.6",
|
||||
"@types/node": "^25.5.0",
|
||||
"@typescript-eslint/eslint-plugin": "^8.57.1",
|
||||
"@typescript-eslint/parser": "^8.57.1",
|
||||
"eslint": "^10.1.0",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"eslint-formatter-unix": "^9.0.1",
|
||||
"eslint-plugin-prettier": "^5.5.5",
|
||||
"prettier": "^3.8.1",
|
||||
"ts-node": "^10.9.2",
|
||||
"typescript": "^5.9.3"
|
||||
"typescript": "^5.9.3",
|
||||
"typescript-eslint": "^8.57.1"
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user