Professional Node.js/TypeScript backend for Mars Base resource monitoring and management system.
- RESTful API with Express.js
- Real-time Updates via Socket.IO
- Interactive API Documentation with Swagger/OpenAPI 3.0
- TypeScript for type safety
- Layered Architecture (Controllers, Services, Repositories)
- In-memory Data Storage with seed data
- CORS Support for frontend integration
- Error Handling middleware
- Request Logging middleware
- Environment Configuration with validation
┌─────────────────────────────────────┐
│ HTTP / WebSocket │
├─────────────────────────────────────┤
│ Routes Layer │
├─────────────────────────────────────┤
│ Controllers Layer │
│ (Request/Response handling) │
├─────────────────────────────────────┤
│ Services Layer │
│ (Business Logic) │
├─────────────────────────────────────┤
│ Repositories Layer │
│ (Data Access Logic) │
├─────────────────────────────────────┤
│ Data Storage │
│ (In-memory with seed data) │
└─────────────────────────────────────┘
src/
├── config/ # Configuration files
│ ├── env.config.ts
│ └── swagger.config.ts
├── controllers/ # Request handlers
│ ├── resource.controller.ts
│ ├── alert.controller.ts
│ └── resupply.controller.ts
├── data/ # Seed data
│ └── seed.data.ts
├── middleware/ # Express middleware
│ ├── error.middleware.ts
│ └── logger.middleware.ts
├── repositories/ # Data access layer
│ ├── resource.repository.ts
│ ├── alert.repository.ts
│ └── resupply.repository.ts
├── routes/ # API routes (with Swagger annotations)
│ ├── resource.routes.ts
│ ├── alert.routes.ts
│ ├── resupply.routes.ts
│ └── index.ts
├── services/ # Business logic
│ ├── resource.service.ts
│ ├── alert.service.ts
│ └── resupply.service.ts
├── socket/ # Socket.IO handlers
│ └── socket.handler.ts
├── types/ # TypeScript types
│ ├── resource.types.ts
│ ├── alert.types.ts
│ └── resupply.types.ts
├── app.ts # Express app setup
└── server.ts # Server entry point
- Runtime: Node.js
- Language: TypeScript
- Framework: Express.js v5
- Real-time: Socket.IO v4
- API Documentation: Swagger UI + swagger-jsdoc (OpenAPI 3.0)
- CORS: cors middleware
- Environment: dotenv
- Development: ts-node-dev
- Node.js 18+ or higher
- npm or pnpm
- Navigate to the backend directory:
cd mars-backend- Install dependencies:
npm install- Create environment file:
cp .env.example .env- Update
.envwith your configuration
Start the development server with hot reload:
npm run devThe server will start on http://localhost:3000
Build the project:
npm run buildStart the production server:
npm startAccess the interactive API documentation at:
http://localhost:3000/api-docs
Features:
- Complete OpenAPI 3.0 specification
- Interactive API testing interface
- Detailed schema definitions for all entities
- Request/response examples
- Try-it-out functionality for all endpoints
http://localhost:3000/api
GET /api/resourcesGET /api/resources/:idGET /api/resources/type/:typePOST /api/resources
Content-Type: application/json
{
"type": "oxygen",
"name": "Oxygen Supply",
"currentLevel": 7200,
"maxCapacity": 10000,
"unit": "kg",
"criticalThreshold": 20,
"warningThreshold": 40
}PUT /api/resources/:id
Content-Type: application/json
{
"currentLevel": 7000
}GET /api/resources/:id/history?limit=100GET /api/alertsGET /api/alerts/unacknowledgedGET /api/alerts/resource/:resourceIdPOST /api/alerts
Content-Type: application/json
{
"resourceId": "res-oxygen-001",
"resourceName": "Oxygen Supply",
"level": "critical",
"message": "Oxygen levels critical"
}PATCH /api/alerts/:id/acknowledge
Content-Type: application/json
{
"acknowledgedBy": "Commander Sarah Chen"
}DELETE /api/alerts/acknowledged/clearGET /api/resupplyGET /api/resupply/status/:statusGET /api/resupply/resource-type/:typePOST /api/resupply
Content-Type: application/json
{
"resourceType": "oxygen",
"quantity": 2000,
"priority": "urgent",
"requestedBy": "Commander Sarah Chen",
"notes": "Emergency resupply needed"
}PATCH /api/resupply/:id
Content-Type: application/json
{
"status": "approved"
}PATCH /api/resupply/:id/approve
Content-Type: application/json
{
"approvedBy": "Mission Control"
}GET /api/healthResponse:
{
"status": "healthy",
"timestamp": "2025-11-29T14:00:00.000Z",
"uptime": 3600
}resources:initial- Initial resources data on connectionalerts:initial- Initial alerts data on connectionresources:updated- All resources updatedresource:updated- Single resource updatedalert:created- New alert createdalert:acknowledged- Alert acknowledgedresupply:created- New resupply request createdresupply:updated- Resupply request updated
resource:subscribe- Subscribe to specific resource updatesresource:unsubscribe- Unsubscribe from resource updates
import io from 'socket.io-client';
const socket = io('http://localhost:3000');
socket.on('connect', () => {
console.log('Connected to server');
});
socket.on('resources:updated', (resources) => {
console.log('Resources updated:', resources);
});
socket.on('alert:created', (alert) => {
console.log('New alert:', alert);
});
socket.emit('resource:subscribe', 'res-oxygen-001');PORT=3000
NODE_ENV=development
CORS_ORIGIN=http://localhost:5173
# Update intervals in milliseconds
RESOURCE_UPDATE_INTERVAL=5000
ALERT_CHECK_INTERVAL=10000The backend automatically simulates resource consumption every 5 seconds (configurable). Each resource decreases based on its consumption rate with slight random variations to simulate real-world conditions.
The system checks resource levels every 10 seconds (configurable) and automatically creates critical alerts when resources fall below their critical thresholds.
All changes to resources, alerts, and resupply requests are automatically broadcast to connected clients via Socket.IO.
Data access logic is isolated in repository classes, making it easy to swap data sources (e.g., from in-memory to database).
Business logic is separated from HTTP handling, enabling reuse and easier testing.
Services receive their dependencies through constructors, following the Dependency Inversion Principle.
Each class has one reason to change:
- Controllers handle HTTP requests
- Services implement business logic
- Repositories manage data access
All errors are caught and formatted consistently:
{
"error": {
"message": "Resource with id xyz not found"
}
}In development mode, stack traces are included.
All HTTP requests are logged with:
- Timestamp
- HTTP method
- URL
- Status code
- Response time
Example:
[2025-11-29T14:00:00.000Z] GET /api/resources 200 - 15ms
- Add database support (MongoDB/PostgreSQL)
- Implement authentication/authorization
- Add input validation with Zod or Joi
- Add unit and integration tests
- Implement rate limiting
- Add data persistence
- Implement caching with Redis
Copyright PERFICIENT - All rights reserved
Built for Mars Base Operations - PERFICIENT Mission Control