insitu-js 0.0.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +110 -0
- package/CREACION_DE_CONTROLADORES_INSITU.md +383 -0
- package/LICENSE +201 -0
- package/README.md +155 -0
- package/changelogs/1.0.1/CENTRALIZED_EXECUTE_MIDDLEWARE_IMPLEMENTATION.md +88 -0
- package/changelogs/1.0.1/DRY.md +525 -0
- package/changelogs/1.0.1/WAF_LOG_MONITOR_IMPLEMENTATION.md +186 -0
- package/controllers/EjemploController.js +165 -0
- package/controllers/HolaController.js +60 -0
- package/docs1.x/ADMIN_EXTENSION_COMMANDS_MANUAL.md +261 -0
- package/docs1.x/ADMIN_EXTENSION_HOOK_EXAMPLE.md +28 -0
- package/docs1.x/ADMIN_EXTENSION_INTEGRATION_MANUAL.md +232 -0
- package/docs1.x/CACHE_REGEX_COMMANDS.md +136 -0
- package/docs1.x/CACHE_SYSTEM_MAP.md +206 -0
- package/docs1.x/QUEUE_CLI_MODULE_MANUAL.md +289 -0
- package/docs1.x/QUEUE_SYSTEM_MANUAL.md +320 -0
- package/docs1.x/ROUTE_CACHE_MODULE_MANUAL.md +205 -0
- package/docs1.x/SESSION_SECURITY_FLAGS.md +174 -0
- package/docs1.x/WAF_MODULE_MANUAL.md +229 -0
- package/docs1.x/an/303/241lisis-completo-insitu-framework.md +213 -0
- package/docs1.x/manual-mvc-completo.md +934 -0
- package/docs1.x/modulos_administracion.md +89 -0
- package/index.js +142 -0
- package/insitu-admin-client/README.md +69 -0
- package/insitu-admin-client/package.json +23 -0
- package/insitu-admin-client.js +257 -0
- package/lib/admin/AdminExtension.js +492 -0
- package/lib/admin/ModuleLoader.js +77 -0
- package/lib/admin/config.js +21 -0
- package/lib/admin/modules/CacheModule.js +145 -0
- package/lib/admin/modules/QueueManagementModule.js +265 -0
- package/lib/admin/modules/RouteCacheModule.js +227 -0
- package/lib/admin/modules/RouteManagerModule.js +531 -0
- package/lib/admin/modules/STATS_MODULE_README.md +113 -0
- package/lib/admin/modules/StatsModule.js +140 -0
- package/lib/admin/modules/SystemModule.js +140 -0
- package/lib/admin/modules/TimeModule.js +95 -0
- package/lib/admin/modules/ViewCacheStatsModule.js +92 -0
- package/lib/admin/modules/WAFModule.js +814 -0
- package/lib/cache/CacheHooks.js +141 -0
- package/lib/core/handler.js +86 -0
- package/lib/core/hooks-handlers/request-hooks-handler.js +108 -0
- package/lib/core/hooks-handlers/route-hooks-handler.js +19 -0
- package/lib/core/hooks-handlers/server-start-hooks-handler.js +31 -0
- package/lib/core/hooks-handlers/static-file-hooks-handler.js +130 -0
- package/lib/core/hooks-handlers/stats-hooks-handler.js +70 -0
- package/lib/core/hooks-handlers/view-hooks-handler.js +37 -0
- package/lib/core/hooks.js +586 -0
- package/lib/core/router.js +198 -0
- package/lib/core/securityEnhancedServer.js +753 -0
- package/lib/core/server.js +984 -0
- package/lib/loader/controllerLoader.js +175 -0
- package/lib/loader/routeDirectoryLoader.js +300 -0
- package/lib/loader/routeLoader.js +340 -0
- package/lib/middleware/auditLogger.js +208 -0
- package/lib/middleware/authenticator.js +565 -0
- package/lib/middleware/compressor.js +557 -0
- package/lib/middleware/cors.js +135 -0
- package/lib/middleware/firewall.js +577 -0
- package/lib/middleware/rateLimiter.js +210 -0
- package/lib/middleware/session.js +309 -0
- package/lib/middleware/validator.js +193 -0
- package/lib/mvc/GenericAdapter.js +136 -0
- package/lib/mvc/MariaDBAdapter.js +315 -0
- package/lib/mvc/MemoryAdapter.js +269 -0
- package/lib/mvc/ModelControllerExample.js +285 -0
- package/lib/mvc/controllerBase.js +352 -0
- package/lib/mvc/modelBase.js +383 -0
- package/lib/mvc/modelManager.js +284 -0
- package/lib/mvc/userModel.js +265 -0
- package/lib/mvc/viewEngine.js +908 -0
- package/lib/queue/GlobalQueueStorage.js +38 -0
- package/lib/queue/QueueSystem.js +451 -0
- package/lib/queue/admin_example.js +114 -0
- package/lib/queue/example.js +268 -0
- package/lib/queue/integration.js +109 -0
- package/lib/router/RouteMatcher.js +362 -0
- package/lib/utils/configParser.js +223 -0
- package/lib/utils/errorHandler.js +123 -0
- package/lib/utils/executeMiddleware.js +35 -0
- package/lib/utils/globalStats.js +16 -0
- package/lib/utils/globalViewCacheInfo.js +16 -0
- package/lib/utils/globalWAFStats.js +60 -0
- package/lib/utils/logger.js +210 -0
- package/lib/utils/mariadbTokenAdapter.js +226 -0
- package/lib/utils/mimeType.js +62 -0
- package/lib/utils/openapiGenerator.js +140 -0
- package/lib/utils/sqliteTokenAdapter.js +224 -0
- package/lib/utils/tokenManager.js +254 -0
- package/package.json +55 -6
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
Todos los cambios relevantes de este framework se documentan en este archivo.
|
|
4
|
+
El versionado sigue SemVer (MAJOR.MINOR.PATCH).
|
|
5
|
+
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## [1.0.1] - 2026-02-13
|
|
9
|
+
|
|
10
|
+
### Refactorización DRY y Mejoras en el WAF - Insitu Framework
|
|
11
|
+
|
|
12
|
+
#### Archivo Nuevo: `lib/utils/executeMiddleware.js`
|
|
13
|
+
- Creación del módulo centralizado `executeMiddleware` para la ejecución de middlewares
|
|
14
|
+
- Implementación del método reutilizable `executeMiddleware(middleware, req, res, nextFn = null)` con manejo de promesas
|
|
15
|
+
|
|
16
|
+
#### Archivos Modificados:
|
|
17
|
+
- `lib/core/server.js`
|
|
18
|
+
- `lib/loader/routeLoader.js`
|
|
19
|
+
- `lib/core/router.js`
|
|
20
|
+
- `lib/security/globalWAFStats.js`
|
|
21
|
+
- `lib/security/firewall.js`
|
|
22
|
+
- `lib/admin/modules/WAFModule.js`
|
|
23
|
+
|
|
24
|
+
#### Implementación de Método Centralizado executeMiddleware
|
|
25
|
+
- Eliminación de múltiples instancias de código repetido para ejecución de middlewares
|
|
26
|
+
- Reemplazo de lógica local con importación y uso del módulo centralizado
|
|
27
|
+
- Actualización del método `use` en el router para usar el método centralizado
|
|
28
|
+
- Implementación de definición dinámica de métodos HTTP en el router
|
|
29
|
+
|
|
30
|
+
#### Implementación de Funcionalidades de Log y Monitor en el WAF
|
|
31
|
+
- Añadida propiedad `monitoredRequests` al objeto global de estadísticas del WAF
|
|
32
|
+
- Implementación completa de la acción "monitor" en el middleware de firewall
|
|
33
|
+
- Almacenamiento de solicitudes monitoreadas en el mapa global `monitoredRequests`
|
|
34
|
+
- Añadido comando `waf-monitored` al módulo de administración WAF
|
|
35
|
+
- Implementación del método `showMonitoredRequests()` para mostrar solicitudes monitoreadas
|
|
36
|
+
- Actualización del comando `waf-logs` para mostrar solicitudes registradas con acción "log"
|
|
37
|
+
|
|
38
|
+
#### Aplicación del Principio DRY (Don't Repeat Yourself)
|
|
39
|
+
- Creación del método `createAuthenticatedHandler()` para manejar lógica de autenticación
|
|
40
|
+
- Implementación de métodos para respuestas HTTP comunes (`sendJsonResponse()`, `sendForbiddenResponse()`, `sendNotFoundResponse()`, `sendRequestTooLargeResponse()`)
|
|
41
|
+
- Uso del método reutilizable `handleError()` en lugar de llamar directamente a ErrorHandler.handle()
|
|
42
|
+
|
|
43
|
+
#### Mejoras en el Manejo de Errores y Configuración
|
|
44
|
+
- Centralización del manejo de errores con el método `handleError()`
|
|
45
|
+
- Creación del método `isJsonRequest()` para verificar tipo de contenido
|
|
46
|
+
- Implementación del método `setStaticFileHeaders()` para configurar headers de archivos estáticos
|
|
47
|
+
|
|
48
|
+
#### Optimizaciones de Estadísticas y Hooks
|
|
49
|
+
- Método `setupResponseCapture()` para capturar datos de respuesta para estadísticas
|
|
50
|
+
- Método `updateRequestProcessingStats()` para actualizar estadísticas de procesamiento
|
|
51
|
+
- Método `registerRouteAndEndpointStats()` para registrar estadísticas de acceso
|
|
52
|
+
- Métodos para manejar eventos de hooks de solicitud (`handleRouteMatched()`, `handleMiddlewareResponseFinished()`)
|
|
53
|
+
|
|
54
|
+
#### Mejoras en Verificaciones y Validaciones
|
|
55
|
+
- Método `isMiddlewareFunction()` para verificar si un middleware es una función
|
|
56
|
+
- Método `isAsyncFunction()` para verificar si una función es asíncrona
|
|
57
|
+
|
|
58
|
+
#### Beneficios Obtenidos
|
|
59
|
+
- Eliminación significativa de código duplicado
|
|
60
|
+
- Mejor mantenibilidad: cambios en lógica común solo se realizan en un lugar
|
|
61
|
+
- Mayor consistencia en el manejo de operaciones repetitivas
|
|
62
|
+
- Funcionalidad completa de las acciones "log" y "monitor" en el WAF
|
|
63
|
+
- Almacenamiento eficiente de solicitudes registradas y monitoreadas
|
|
64
|
+
- Visibilidad mejorada a través de comandos específicos (`waf-logs`, `waf-monitored`)
|
|
65
|
+
- Reducción de posibles errores por inconsistencias
|
|
66
|
+
- Claridad mejorada del código
|
|
67
|
+
|
|
68
|
+
---
|
|
69
|
+
|
|
70
|
+
## [1.0.0] - 2026-02-12
|
|
71
|
+
|
|
72
|
+
### Consolidated Release - Insitu Framework
|
|
73
|
+
|
|
74
|
+
#### Framework Renaming
|
|
75
|
+
- Cambio de nombre del framework de "JERK Framework" a "Insitu Framework"
|
|
76
|
+
- Actualización de todos los nombres de paquetes, referencias y documentación
|
|
77
|
+
- Renombrado de archivos y directorios relacionados con el antiguo nombre
|
|
78
|
+
|
|
79
|
+
#### Version Standardization
|
|
80
|
+
- Consolidación de todas las versiones anteriores a la versión única 1.0.0
|
|
81
|
+
- Actualización de todos los números de versión en comentarios, documentación y código
|
|
82
|
+
- Unificación de la numeración de versiones en todos los componentes
|
|
83
|
+
|
|
84
|
+
#### Architecture & Core Features
|
|
85
|
+
- Sistema de enrutamiento avanzado con soporte para rutas estáticas y parametrizadas
|
|
86
|
+
- Arquitectura modular con componentes desacoplados
|
|
87
|
+
- Sistema de hooks y filters para extensibilidad
|
|
88
|
+
- Motor de vistas con soporte para includes, variables y filtros
|
|
89
|
+
- Sistema de modelos con soporte para diferentes adaptadores (memoria, MariaDB, SQLite)
|
|
90
|
+
|
|
91
|
+
#### Security & Performance
|
|
92
|
+
- Firewall WAF integrado con reglas configurables
|
|
93
|
+
- Sistema de autenticación con múltiples estrategias (JWT, API Keys, Sesiones)
|
|
94
|
+
- Sistema de sesiones con cookies seguras
|
|
95
|
+
- Optimizaciones de rendimiento con índices y caché
|
|
96
|
+
- Protección contra ataques XSS y SQL Injection
|
|
97
|
+
|
|
98
|
+
#### Administration & Monitoring
|
|
99
|
+
- Extensión de administración con servidor TCP local
|
|
100
|
+
- Módulos de administración para gestión de rutas, vistas y estadísticas
|
|
101
|
+
- Sistema de colas con soporte para múltiples colas concurrentes
|
|
102
|
+
- Monitorización en tiempo real de métricas del servidor
|
|
103
|
+
|
|
104
|
+
#### Development Experience
|
|
105
|
+
- CLI de administración con autocompletado
|
|
106
|
+
- Generador interactivo de controladores
|
|
107
|
+
- Carga de rutas desde archivos JSON o programáticamente
|
|
108
|
+
- Documentación completa y ejemplos de uso
|
|
109
|
+
|
|
110
|
+
---
|
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
# Guía para Crear Controladores en el Framework Insitu
|
|
2
|
+
|
|
3
|
+
## Introducción
|
|
4
|
+
|
|
5
|
+
Los controladores en el framework Insitu son componentes fundamentales que forman parte del patrón MVC (Modelo-Vista-Controlador). Son responsables de manejar las solicitudes HTTP, interactuar con los modelos para obtener o manipular datos, y devolver respuestas apropiadas al cliente.
|
|
6
|
+
|
|
7
|
+
## Estructura Básica de un Controlador
|
|
8
|
+
|
|
9
|
+
Un controlador en Insitu debe extender la clase `ControllerBase` que proporciona funcionalidades comunes como:
|
|
10
|
+
|
|
11
|
+
- Manejo de vistas y motores de plantillas
|
|
12
|
+
- Acceso a datos de solicitud (query, body, params)
|
|
13
|
+
- Métodos para respuesta (JSON, vistas, redirecciones)
|
|
14
|
+
- Carga y manejo de modelos
|
|
15
|
+
|
|
16
|
+
### Ejemplo Básico de Controlador
|
|
17
|
+
|
|
18
|
+
```javascript
|
|
19
|
+
const { ControllerBase } = require('insitu');
|
|
20
|
+
|
|
21
|
+
class EjemploController extends ControllerBase {
|
|
22
|
+
constructor() {
|
|
23
|
+
super();
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Método para manejar una solicitud GET
|
|
27
|
+
async index(req, res) {
|
|
28
|
+
// Establecer variables para la vista
|
|
29
|
+
this.set('titulo', 'Página de Inicio');
|
|
30
|
+
this.set('mensaje', '¡Bienvenido al framework Insitu!');
|
|
31
|
+
|
|
32
|
+
// Renderizar una vista
|
|
33
|
+
this.render(res, 'inicio', {
|
|
34
|
+
usuario: 'Desarrollador',
|
|
35
|
+
fecha: new Date().toISOString()
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Método para manejar una solicitud POST
|
|
40
|
+
async crear(req, res) {
|
|
41
|
+
const datos = req.body;
|
|
42
|
+
|
|
43
|
+
// Aquí iría la lógica para crear un recurso
|
|
44
|
+
// Por ejemplo, usando un modelo
|
|
45
|
+
|
|
46
|
+
this.json(res, {
|
|
47
|
+
success: true,
|
|
48
|
+
message: 'Recurso creado exitosamente',
|
|
49
|
+
data: datos
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
module.exports = EjemploController;
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Componentes Importantes
|
|
58
|
+
|
|
59
|
+
### ControllerBase
|
|
60
|
+
|
|
61
|
+
La clase base `ControllerBase` proporciona varios métodos útiles:
|
|
62
|
+
|
|
63
|
+
- `set(key, value)` - Establece variables para la vista
|
|
64
|
+
- `view(viewName, data, options)` - Renderiza una vista sin enviarla como respuesta
|
|
65
|
+
- `render(res, viewName, data, options)` - Renderiza una vista y la envía como respuesta HTTP
|
|
66
|
+
- `partial(viewName, data)` - Renderiza una vista parcial (sin layout)
|
|
67
|
+
- `redirect(res, url)` - Redirecciona a otra URL
|
|
68
|
+
- `json(res, data, statusCode)` - Envía una respuesta JSON
|
|
69
|
+
- `input(key, defaultValue)` - Obtiene un valor de la solicitud (query, body o params)
|
|
70
|
+
- `loadModel(modelName, options)` - Carga un modelo para su uso en el controlador
|
|
71
|
+
|
|
72
|
+
### Interacción con Modelos
|
|
73
|
+
|
|
74
|
+
Los controladores pueden interactuar con modelos para gestionar datos:
|
|
75
|
+
|
|
76
|
+
```javascript
|
|
77
|
+
const { ControllerBase } = require('insitu');
|
|
78
|
+
|
|
79
|
+
class UsuarioController extends ControllerBase {
|
|
80
|
+
constructor() {
|
|
81
|
+
super();
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async listar(req, res) {
|
|
85
|
+
try {
|
|
86
|
+
// Cargar el modelo de usuario
|
|
87
|
+
const userModel = this.loadModel('User');
|
|
88
|
+
|
|
89
|
+
// Obtener todos los usuarios
|
|
90
|
+
const usuarios = await userModel.find({});
|
|
91
|
+
|
|
92
|
+
// Pasar los usuarios a la vista
|
|
93
|
+
this.set('usuarios', usuarios);
|
|
94
|
+
this.render(res, 'usuarios/lista');
|
|
95
|
+
} catch (error) {
|
|
96
|
+
this.json(res, { error: error.message }, 500);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async crear(req, res) {
|
|
101
|
+
try {
|
|
102
|
+
const userData = req.body;
|
|
103
|
+
|
|
104
|
+
// Cargar el modelo de usuario
|
|
105
|
+
const userModel = this.loadModel('User');
|
|
106
|
+
|
|
107
|
+
// Crear un nuevo usuario
|
|
108
|
+
const nuevoUsuario = await userModel.create(userData);
|
|
109
|
+
|
|
110
|
+
this.json(res, {
|
|
111
|
+
success: true,
|
|
112
|
+
data: nuevoUsuario
|
|
113
|
+
}, 201);
|
|
114
|
+
} catch (error) {
|
|
115
|
+
this.json(res, { error: error.message }, 500);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
module.exports = UsuarioController;
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
## Definición de Rutas
|
|
124
|
+
|
|
125
|
+
Para conectar tus controladores con rutas, puedes usar el sistema de enrutamiento de Insitu:
|
|
126
|
+
|
|
127
|
+
### En un archivo de rutas (por ejemplo, routes.json):
|
|
128
|
+
|
|
129
|
+
```json
|
|
130
|
+
{
|
|
131
|
+
"routes": [
|
|
132
|
+
{
|
|
133
|
+
"method": "GET",
|
|
134
|
+
"path": "/usuarios",
|
|
135
|
+
"handler": "./controllers/UsuarioController.listar"
|
|
136
|
+
},
|
|
137
|
+
{
|
|
138
|
+
"method": "POST",
|
|
139
|
+
"path": "/usuarios",
|
|
140
|
+
"handler": "./controllers/UsuarioController.crear"
|
|
141
|
+
},
|
|
142
|
+
{
|
|
143
|
+
"method": "GET",
|
|
144
|
+
"path": "/usuarios/:id",
|
|
145
|
+
"handler": "./controllers/UsuarioController.obtenerPorId"
|
|
146
|
+
}
|
|
147
|
+
]
|
|
148
|
+
}
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
### O directamente en tu código de inicialización:
|
|
152
|
+
|
|
153
|
+
```javascript
|
|
154
|
+
const { Insitu, Router } = require('insitu');
|
|
155
|
+
const UsuarioController = require('./controllers/UsuarioController');
|
|
156
|
+
|
|
157
|
+
const app = new Insitu();
|
|
158
|
+
const router = new Router();
|
|
159
|
+
|
|
160
|
+
const usuarioController = new UsuarioController();
|
|
161
|
+
|
|
162
|
+
router.get('/usuarios', (req, res) => {
|
|
163
|
+
usuarioController.listar(req, res);
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
router.post('/usuarios', (req, res) => {
|
|
167
|
+
usuarioController.crear(req, res);
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
app.use(router);
|
|
171
|
+
|
|
172
|
+
app.listen(3000, () => {
|
|
173
|
+
console.log('Servidor corriendo en puerto 3000');
|
|
174
|
+
});
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
### Importante: Manejo de Contexto de los Métodos
|
|
178
|
+
|
|
179
|
+
Cuando se exportan métodos de un controlador para ser usados como handlers de rutas, es crítico mantener el contexto `this` correcto. Si no se hace correctamente, métodos como `this.json()`, `this.set()`, `this.input()`, etc., no funcionarán.
|
|
180
|
+
|
|
181
|
+
**Forma Incorrecta:**
|
|
182
|
+
```javascript
|
|
183
|
+
// Esto causará un error "Cannot read property 'json' of undefined"
|
|
184
|
+
module.exports = new UsuarioController();
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
**Forma Correcta:**
|
|
188
|
+
```javascript
|
|
189
|
+
// Crear una instancia del controlador
|
|
190
|
+
const usuarioController = new UsuarioController();
|
|
191
|
+
|
|
192
|
+
// Asegurar que todos los métodos tengan el contexto correcto
|
|
193
|
+
module.exports = {
|
|
194
|
+
listar: usuarioController.listar.bind(usuarioController),
|
|
195
|
+
crear: usuarioController.crear.bind(usuarioController),
|
|
196
|
+
obtenerPorId: usuarioController.obtenerPorId.bind(usuarioController)
|
|
197
|
+
};
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
Esto es necesario porque cuando el cargador de rutas obtiene una función específica de un objeto y la llama directamente, pierde el contexto `this`. Usando `.bind()`, nos aseguramos de que `this` siempre se refiera a la instancia correcta del controlador.
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
## Buenas Prácticas
|
|
204
|
+
|
|
205
|
+
### 1. Organización de Archivos
|
|
206
|
+
|
|
207
|
+
Organiza tus controladores en una estructura de directorios clara:
|
|
208
|
+
|
|
209
|
+
```
|
|
210
|
+
proyecto/
|
|
211
|
+
├── controllers/
|
|
212
|
+
│ ├── UsuarioController.js
|
|
213
|
+
│ ├── ProductoController.js
|
|
214
|
+
│ └── HomeController.js
|
|
215
|
+
├── models/
|
|
216
|
+
│ ├── User.js
|
|
217
|
+
│ └── Product.js
|
|
218
|
+
├── views/
|
|
219
|
+
│ ├── home/
|
|
220
|
+
│ │ └── index.html
|
|
221
|
+
│ └── usuarios/
|
|
222
|
+
│ ├── lista.html
|
|
223
|
+
│ └── detalle.html
|
|
224
|
+
└── routes/
|
|
225
|
+
└── routes.json
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
### 2. Manejo de Errores
|
|
229
|
+
|
|
230
|
+
Siempre implementa manejo de errores adecuado:
|
|
231
|
+
|
|
232
|
+
```javascript
|
|
233
|
+
async listar(req, res) {
|
|
234
|
+
try {
|
|
235
|
+
const modelo = this.loadModel('MiModelo');
|
|
236
|
+
const datos = await modelo.find({});
|
|
237
|
+
this.json(res, { success: true, data: datos });
|
|
238
|
+
} catch (error) {
|
|
239
|
+
console.error('Error en listar:', error);
|
|
240
|
+
this.json(res, {
|
|
241
|
+
success: false,
|
|
242
|
+
error: 'Ocurrió un error al procesar la solicitud'
|
|
243
|
+
}, 500);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
### 3. Validación de Datos
|
|
249
|
+
|
|
250
|
+
Utiliza el middleware de validación de Insitu para validar entradas:
|
|
251
|
+
|
|
252
|
+
```javascript
|
|
253
|
+
const { Validator } = require('insitu');
|
|
254
|
+
|
|
255
|
+
// En tu archivo de rutas
|
|
256
|
+
router.post('/usuarios',
|
|
257
|
+
Validator.validate({
|
|
258
|
+
body: {
|
|
259
|
+
nombre: { type: 'string', required: true, minLength: 2 },
|
|
260
|
+
email: { type: 'string', required: true, format: 'email' },
|
|
261
|
+
edad: { type: 'number', min: 0, max: 120 }
|
|
262
|
+
}
|
|
263
|
+
}),
|
|
264
|
+
(req, res) => {
|
|
265
|
+
usuarioController.crear(req, res);
|
|
266
|
+
}
|
|
267
|
+
);
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
### 4. Uso de Métodos HTTP Apropiados
|
|
271
|
+
|
|
272
|
+
Sigue las convenciones REST para el uso de métodos HTTP:
|
|
273
|
+
|
|
274
|
+
- `GET` - Obtener recursos
|
|
275
|
+
- `POST` - Crear nuevos recursos
|
|
276
|
+
- `PUT/PATCH` - Actualizar recursos existentes
|
|
277
|
+
- `DELETE` - Eliminar recursos
|
|
278
|
+
|
|
279
|
+
## Ejemplo Completo
|
|
280
|
+
|
|
281
|
+
Aquí tienes un ejemplo completo de un controlador para gestionar productos:
|
|
282
|
+
|
|
283
|
+
```javascript
|
|
284
|
+
const { ControllerBase } = require('insitu');
|
|
285
|
+
|
|
286
|
+
class ProductoController extends ControllerBase {
|
|
287
|
+
constructor() {
|
|
288
|
+
super();
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// Obtener todos los productos
|
|
292
|
+
async listar(req, res) {
|
|
293
|
+
try {
|
|
294
|
+
const productoModel = this.loadModel('Producto');
|
|
295
|
+
const productos = await productoModel.find({});
|
|
296
|
+
|
|
297
|
+
this.set('productos', productos);
|
|
298
|
+
this.set('titulo', 'Lista de Productos');
|
|
299
|
+
this.render(res, 'productos/lista');
|
|
300
|
+
} catch (error) {
|
|
301
|
+
this.json(res, { error: error.message }, 500);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// Obtener un producto por ID
|
|
306
|
+
async obtenerPorId(req, res) {
|
|
307
|
+
try {
|
|
308
|
+
const id = this.input('id');
|
|
309
|
+
const productoModel = this.loadModel('Producto');
|
|
310
|
+
const producto = await productoModel.findOne({ id: parseInt(id) });
|
|
311
|
+
|
|
312
|
+
if (!producto) {
|
|
313
|
+
res.writeHead(404, { 'Content-Type': 'application/json' });
|
|
314
|
+
res.end(JSON.stringify({ error: 'Producto no encontrado' }));
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
this.json(res, { success: true, data: producto });
|
|
319
|
+
} catch (error) {
|
|
320
|
+
this.json(res, { error: error.message }, 500);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// Crear un nuevo producto
|
|
325
|
+
async crear(req, res) {
|
|
326
|
+
try {
|
|
327
|
+
const productoData = this.allInput();
|
|
328
|
+
const productoModel = this.loadModel('Producto');
|
|
329
|
+
const nuevoProducto = await productoModel.create(productoData);
|
|
330
|
+
|
|
331
|
+
this.json(res, {
|
|
332
|
+
success: true,
|
|
333
|
+
data: nuevoProducto
|
|
334
|
+
}, 201);
|
|
335
|
+
} catch (error) {
|
|
336
|
+
this.json(res, { error: error.message }, 500);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// Actualizar un producto
|
|
341
|
+
async actualizar(req, res) {
|
|
342
|
+
try {
|
|
343
|
+
const id = this.input('id');
|
|
344
|
+
const productoData = this.allInput();
|
|
345
|
+
const productoModel = this.loadModel('Producto');
|
|
346
|
+
|
|
347
|
+
const resultado = await productoModel.update({ id: parseInt(id) }, productoData);
|
|
348
|
+
|
|
349
|
+
this.json(res, {
|
|
350
|
+
success: true,
|
|
351
|
+
message: 'Producto actualizado',
|
|
352
|
+
affectedRows: resultado
|
|
353
|
+
});
|
|
354
|
+
} catch (error) {
|
|
355
|
+
this.json(res, { error: error.message }, 500);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// Eliminar un producto
|
|
360
|
+
async eliminar(req, res) {
|
|
361
|
+
try {
|
|
362
|
+
const id = this.input('id');
|
|
363
|
+
const productoModel = this.loadModel('Producto');
|
|
364
|
+
|
|
365
|
+
const resultado = await productoModel.delete({ id: parseInt(id) });
|
|
366
|
+
|
|
367
|
+
this.json(res, {
|
|
368
|
+
success: true,
|
|
369
|
+
message: 'Producto eliminado',
|
|
370
|
+
deletedRows: resultado
|
|
371
|
+
});
|
|
372
|
+
} catch (error) {
|
|
373
|
+
this.json(res, { error: error.message }, 500);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
module.exports = ProductoController;
|
|
379
|
+
```
|
|
380
|
+
|
|
381
|
+
## Conclusión
|
|
382
|
+
|
|
383
|
+
Crear controladores en el framework Insitu es sencillo gracias a la clase `ControllerBase` que proporciona funcionalidades comunes. Recuerda seguir las buenas prácticas para mantener tu código limpio, seguro y mantenible. La arquitectura MVC del framework te permite separar claramente la lógica de negocio (modelos), la presentación (vistas) y el flujo de control (controladores).
|
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|