6.0 KiB
6.0 KiB
Guía de Desarrollo - Nexus
🏗️ Arquitectura
La aplicación sigue una arquitectura limpia y modular:
┌─────────────────────────────────────┐
│ index.ts (Entry Point) │
└──────────────┬──────────────────────┘
│
┌──────────────▼──────────────────────┐
│ core/Application.ts │
│ (Orquestación y ciclo de vida) │
└──────────┬───────────────┬──────────┘
│ │
┌──────────▼──────┐ ┌─────▼──────────┐
│ Services │ │ Utils │
│ (Lógica de │ │ (Helpers) │
│ negocio) │ │ │
└──────────────────┘ └────────────────┘
📝 Crear un Nuevo Servicio
1. Crear el archivo del servicio
// src/services/MiServicio.ts
import logger from '../utils/logger';
import { ServiceResponse } from '../types';
export class MiServicio {
async hacerAlgo(parametro: string): Promise<ServiceResponse<string>> {
try {
logger.debug('MiServicio procesando...', { parametro });
// Tu lógica aquí
const resultado = `Procesado: ${parametro}`;
return {
success: true,
data: resultado,
timestamp: new Date(),
};
} catch (error) {
logger.error('Error en MiServicio:', error);
return {
success: false,
error: error instanceof Error ? error.message : 'Error desconocido',
timestamp: new Date(),
};
}
}
}
2. Usar el servicio en tu aplicación
// src/index.ts
import { MiServicio } from './services/MiServicio';
const servicio = new MiServicio();
const resultado = await servicio.hacerAlgo('datos');
🔧 Agregar Configuraciones
1. Agregar variables de entorno
# .env
MI_VARIABLE=valor
2. Actualizar el tipo AppConfig
// src/types/index.ts
export interface AppConfig {
// ...existentes
miVariable: string;
}
3. Cargar la configuración
// src/config/index.ts
export const config: AppConfig = {
// ...existentes
miVariable: process.env.MI_VARIABLE || 'default',
};
🛠️ Utilidades Comunes
Logger
import logger from './utils/logger';
logger.debug('Mensaje de depuración');
logger.info('Información');
logger.warn('Advertencia');
logger.error('Error', error);
Manejo de Errores
try {
// código
} catch (error) {
logger.error('Descripción del error:', error);
throw error; // o manejar de otra forma
}
🚀 Agregar API REST (Opcional)
1. Instalar Express
npm install express
npm install -D @types/express
2. Crear servidor HTTP
// src/core/Server.ts
import express from 'express';
import { config } from '../config';
import logger from '../utils/logger';
export class Server {
private app = express();
constructor() {
this.setupMiddleware();
this.setupRoutes();
}
private setupMiddleware() {
this.app.use(express.json());
}
private setupRoutes() {
this.app.get('/health', (req, res) => {
res.json({ status: 'ok', timestamp: new Date() });
});
}
async start() {
return new Promise<void>((resolve) => {
this.app.listen(config.appPort, () => {
logger.info(`🌐 Servidor escuchando en puerto ${config.appPort}`);
resolve();
});
});
}
}
3. Integrar en Application.ts
// src/core/Application.ts
import { Server } from './Server';
export class Application {
private server?: Server;
async initialize(): Promise<void> {
// ...código existente
this.server = new Server();
await this.server.start();
}
}
🗄️ Agregar Base de Datos
PostgreSQL con Prisma
npm install @prisma/client
npm install -D prisma
npx prisma init
MongoDB con Mongoose
npm install mongoose
npm install -D @types/mongoose
🧪 Agregar Tests
1. Instalar Jest
npm install -D jest @types/jest ts-jest
2. Configurar Jest
// jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
roots: ['<rootDir>/src'],
testMatch: ['**/__tests__/**/*.ts', '**/?(*.)+(spec|test).ts'],
};
3. Crear tests
// src/services/__tests__/ExampleService.test.ts
import { ExampleService } from '../ExampleService';
describe('ExampleService', () => {
it('debería procesar correctamente', async () => {
const service = new ExampleService();
const resultado = await service.execute('test');
expect(resultado.success).toBe(true);
expect(resultado.data).toContain('test');
});
});
📦 Buenas Prácticas
- Siempre usa tipos TypeScript - No uses
any - Registra eventos importantes - Usa el logger liberalmente
- Maneja errores apropiadamente - Nunca dejes un catch vacío
- Escribe código limpio - Usa prettier y eslint
- Documenta funciones complejas - Usa JSDoc
- Separa responsabilidades - Un servicio, una responsabilidad
- Usa variables de entorno - Para configuraciones sensibles
🔄 Flujo de Trabajo Recomendado
- Desarrollo:
npm run dev - Linting:
npm run lint - Formateo:
npm run format - Compilación:
npm run build - Producción:
npm start