This document outlines the architecture and code organization of the PowerPulse backend server.
The backend code is organized into the following directories:
- db/: Database setup and configuration
- middleware/: Express middleware
- routes/: API route handlers
- utils/: Utility functions
The server is built using Express.js and uses SQLite for data storage. The main entry points are:
- server.js: The entry point that starts the Express server
- app.js: Sets up the Express application, middleware, and routes
The database is set up in db/index.js
. It uses SQLite with the following tables:
- users: User accounts with authentication information
- nut_servers: NUT server configurations
- ups_systems: UPS systems monitored by the application
- battery_history: Historical battery charge data for UPS systems
Authentication is handled using JWT (JSON Web Tokens). The authentication middleware and routes are in:
- middleware/auth.js: JWT verification middleware
- routes/auth.js: Authentication routes (login, register, setup)
The API is organized into the following route modules:
GET /api/auth/check-setup
: Check if initial setup is requiredPOST /api/auth/setup
: Perform initial setup (create admin user and NUT server)POST /api/auth/login
: User loginPOST /api/auth/register
: Register a new user (admin only)
GET /api/nut/servers
: Get all NUT serversGET /api/nut/servers/:id
: Get a specific NUT serverPOST /api/nut/servers
: Add a new NUT serverPUT /api/nut/servers/:id
: Update a NUT serverDELETE /api/nut/servers/:id
: Delete a NUT serverPOST /api/nut/servers/:id/test
: Test connection to a NUT serverGET /api/nut/config
: Get NUT server configuration (legacy)PUT /api/nut/config
: Update NUT server configuration (legacy)
GET /api/ups/systems
: Get all UPS systemsGET /api/ups/systems/:id
: Get a specific UPS systemPOST /api/ups/systems
: Add a new UPS systemPUT /api/ups/systems/:id
: Update a UPS systemDELETE /api/ups/systems/:id
: Delete a UPS systemPOST /api/ups/systems/:id/battery
: Record battery charge for a UPS systemGET /api/ups/systems/:id/battery
: Get battery history for a UPS system
GET /api/users
: Get all users (admin only)GET /api/users/:id
: Get a specific userPUT /api/users/:id
: Update a userDELETE /api/users/:id
: Delete a user
The utils/nutClient.js
module provides utilities for interacting with Network UPS Tools (NUT) servers:
getNutClient
: Get a NUT client connectiongetUpsListFromNutServer
: Get the list of UPS devices from a NUT servergetUpsVariables
: Get UPS variables from a NUT servergetNutUpsData
: Get UPS data from a NUT server
The server uses a consistent error handling approach:
- HTTP status codes for different error types
- Detailed error messages in the response
- Console logging for server-side errors
- JWT-based authentication
- Role-based authorization (admin vs. regular user)
- Protected routes that require authentication