Skip to main content

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

Framework

Express.js 4.x

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:
Helmet - Security headers configuration
app.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 Sharing
const 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
};

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:
  1. Environment Variables - Load and validate configuration
  2. API Key Validation - Verify Anthropic API key format
  3. Database Connection - Connect to MongoDB
  4. Claude API Test - Validate connection to Claude API
  5. HTTP Server - Create server with Express app
  6. Socket.IO Setup - Initialize WebSocket server
  7. Scheduled Tasks - Start cron jobs (if enabled)
  8. 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 middlewareLocation: src/routes/

Controllers

Handle HTTP requests/responses and input validationLocation: src/controllers/

Services

Contain business logic and interact with modelsLocation: 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

Build docs developers (and LLMs) love