Overview
CUIDO Backend is built on a modern, scalable architecture using Node.js, Express.js, and MongoDB. The system follows the MVC (Model-View-Controller) pattern with a clear separation between routes, controllers, and services.
Technology Stack
Runtime Node.js with ES Modules
Database MongoDB with Mongoose ODM
AI Integration Claude API (Anthropic)
Application Structure
The application is initialized in src/app.js and follows a layered architecture:
// Core Express app setup (src/app.js)
import express from 'express' ;
import cors from 'cors' ;
import helmet from 'helmet' ;
import compression from 'compression' ;
import rateLimit from 'express-rate-limit' ;
const app = express ();
Middleware Stack
The application uses a comprehensive middleware stack for security and performance:
Security
Rate Limiting
Compression & Parsing
Helmet - Security headers configurationapp . use ( helmet ({
contentSecurityPolicy: {
directives: {
defaultSrc: [ "'self'" ],
styleSrc: [ "'self'" , "'unsafe-inline'" ],
scriptSrc: [ "'self'" ],
imgSrc: [ "'self'" , "data:" , "https:" ],
},
},
hsts: {
maxAge: 31536000 ,
includeSubDomains: true ,
preload: true
}
}));
CORS - Cross-Origin Resource Sharingconst corsOptions = {
origin : function ( origin , callback ) {
const allowedOrigins = process . env . ALLOWED_ORIGINS ?. split ( ',' ) || [
'http://localhost:3000' ,
'http://localhost:5173' ,
'http://localhost:8080'
];
if ( ! origin || allowedOrigins . includes ( origin )) {
callback ( null , true );
} else {
callback ( new Error ( 'No permitido por CORS' ));
}
},
methods: [ 'GET' , 'POST' , 'PUT' , 'DELETE' , 'OPTIONS' ],
allowedHeaders: [ 'Content-Type' , 'Authorization' ],
credentials: true
};
Rate Limiter - Prevents abuse and DDoS attacksconst limiter = rateLimit ({
windowMs: parseInt ( process . env . RATE_LIMIT_WINDOW_MS ) || 15 * 60 * 1000 ,
max: parseInt ( process . env . RATE_LIMIT_MAX_REQUESTS ) || 100 ,
message: {
success: false ,
message: 'Demasiadas solicitudes. Intenta más tarde.' ,
retryAfter: Math . ceil (( parseInt ( process . env . RATE_LIMIT_WINDOW_MS ) || 900000 ) / 1000 )
},
standardHeaders: true ,
legacyHeaders: false
});
app . use ( '/api/' , limiter );
Default: 100 requests per 15 minutes per IP address
Body Parsing - JSON with validationapp . use ( express . json ({
limit: '10mb' ,
verify : ( req , res , buf ) => {
try {
JSON . parse ( buf );
} catch ( e ) {
res . status ( 400 ). json ({
success: false ,
message: 'JSON inválido'
});
}
}
}));
Compression - Response compression for better performance
Real-time Features with Socket.IO
CUIDO integrates Socket.IO for real-time notifications and updates:
// server.js
import { createServer } from 'http' ;
import { Server } from 'socket.io' ;
const httpServer = createServer ( app );
const io = new Server ( httpServer , {
cors: {
origin: process . env . SOCKET_IO_CORS_ORIGINS ?. split ( ',' ) || [
'http://localhost:3000' ,
'http://localhost:5173' ,
'http://localhost:8080'
],
methods: [ 'GET' , 'POST' ],
credentials: true
}
});
// Socket.IO event handlers
io . on ( 'connection' , ( socket ) => {
console . log ( 'Cliente conectado:' , socket . id );
socket . on ( 'join-hospital' , ( hospitalId ) => {
socket . join ( `hospital- ${ hospitalId } ` );
});
socket . on ( 'join-department' , ( departmentId ) => {
socket . join ( `department- ${ departmentId } ` );
});
socket . on ( 'disconnect' , () => {
console . log ( 'Cliente desconectado:' , socket . id );
});
});
// Make io globally available
global . io = io ;
Socket.IO enables real-time features like instant alerts, live wellness updates, and instant notifications for high-risk employee detection.
Server Initialization
The server startup process includes validation and health checks:
Environment Variables - Load and validate configuration
API Key Validation - Verify Anthropic API key format
Database Connection - Connect to MongoDB
Claude API Test - Validate connection to Claude API
HTTP Server - Create server with Express app
Socket.IO Setup - Initialize WebSocket server
Scheduled Tasks - Start cron jobs (if enabled)
Graceful Shutdown - Register SIGTERM/SIGINT handlers
async function startServer () {
// Validate API keys
if ( ! process . env . ANTHROPIC_API_KEY ) {
logger . error ( 'ANTHROPIC_API_KEY not configured' );
process . exit ( 1 );
}
// Connect to database
await connectDB ();
logger . info ( 'Connected to database' );
// Validate Claude API
const claudeConnected = await claudeService . validateConnection ();
if ( claudeConnected ) {
logger . info ( 'Claude API validated' );
}
// Start HTTP server
const server = httpServer . listen ( PORT , () => {
logger . info ( `Server running on port ${ PORT } ` );
});
// Initialize cron jobs
if ( process . env . ENABLE_CRON_JOBS === 'true' ) {
scheduledTasks . init ();
}
}
MVC Pattern Implementation
CUIDO follows the Model-View-Controller pattern:
Layer Responsibilities
Routes Define API endpoints and apply middleware Location: src/routes/
Controllers Handle HTTP requests/responses and input validation Location: src/controllers/
Services Contain business logic and interact with models Location: src/services/
Error Handling
Centralized error handling with custom middleware:
// Unhandled routes
app . use ( notFound );
// Global error handler
app . use ( errorHandler );
All async route handlers are wrapped with asyncHandler utility to catch errors and pass them to the error middleware.
Health Check Endpoint
Monitor service health:
app . get ( '/health' , ( req , res ) => {
res . status ( 200 ). json ({
success: true ,
message: 'Servicio funcionando correctamente' ,
timestamp: new Date (). toISOString (),
environment: process . env . NODE_ENV || 'development'
});
});
Logging
Structured logging with Morgan and custom logger:
const morganFormat = process . env . NODE_ENV === 'production' ? 'combined' : 'dev' ;
app . use ( morgan ( morganFormat , {
stream: {
write : ( message ) => logger . info ( message . trim ())
}
}));
Next Steps
Authentication Learn about JWT authentication and role-based access control
Modules Overview Explore the 5 CUIDO modules and their architecture