Nexus/DEVELOPMENT.md

262 lines
6.0 KiB
Markdown

# 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
```typescript
// 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
```typescript
// 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
```bash
# .env
MI_VARIABLE=valor
```
### 2. Actualizar el tipo AppConfig
```typescript
// src/types/index.ts
export interface AppConfig {
// ...existentes
miVariable: string;
}
```
### 3. Cargar la configuración
```typescript
// src/config/index.ts
export const config: AppConfig = {
// ...existentes
miVariable: process.env.MI_VARIABLE || 'default',
};
```
## 🛠️ Utilidades Comunes
### Logger
```typescript
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
```typescript
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
```bash
npm install express
npm install -D @types/express
```
### 2. Crear servidor HTTP
```typescript
// 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
```typescript
// 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
```bash
npm install @prisma/client
npm install -D prisma
npx prisma init
```
### MongoDB con Mongoose
```bash
npm install mongoose
npm install -D @types/mongoose
```
## 🧪 Agregar Tests
### 1. Instalar Jest
```bash
npm install -D jest @types/jest ts-jest
```
### 2. Configurar Jest
```javascript
// jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
roots: ['<rootDir>/src'],
testMatch: ['**/__tests__/**/*.ts', '**/?(*.)+(spec|test).ts'],
};
```
### 3. Crear tests
```typescript
// 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
1. **Siempre usa tipos TypeScript** - No uses `any`
2. **Registra eventos importantes** - Usa el logger liberalmente
3. **Maneja errores apropiadamente** - Nunca dejes un catch vacío
4. **Escribe código limpio** - Usa prettier y eslint
5. **Documenta funciones complejas** - Usa JSDoc
6. **Separa responsabilidades** - Un servicio, una responsabilidad
7. **Usa variables de entorno** - Para configuraciones sensibles
## 🔄 Flujo de Trabajo Recomendado
1. **Desarrollo**: `npm run dev`
2. **Linting**: `npm run lint`
3. **Formateo**: `npm run format`
4. **Compilación**: `npm run build`
5. **Producción**: `npm start`
## 📚 Recursos Adicionales
- [TypeScript Handbook](https://www.typescriptlang.org/docs/)
- [Node.js Best Practices](https://github.com/goldbergyoni/nodebestpractices)
- [Clean Architecture](https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html)