'use strict' // Dependencies const express = require('express') const { logMessage, errorMessage } = require('../lib/logger') const logRoute = require('../middleware/logRoute') const testValidUser = require('../middleware/testValidUser') // Server state let server let serverStarted = false let serverClosing = false // Setup error handling const unhandledError = (err) => { // Log the errors errorMessage('router', err) // Only clean up once if (serverClosing) { return } serverClosing = true // If server has started, close it down if (serverStarted) { server.close(() => { process.exit(1) }) } } process.on('uncaughtException', unhandledError) process.on('unhandledRejection', unhandledError) const app = express() // Middlewares app.use(express.json()) app.use(express.static('public')) app.use(express.urlencoded({ extended: true })) // API Routes app.use('/api', logRoute, testValidUser, require('./apiRoute')) // Add non API routes here if needed // Common error handlers app.use((req, res, next) => { logMessage('router', `Route not found: ${req.url}`) return res.status(404).json({ error: `Route not found: ${req.url}` }) }) app.use((err, req, res, next) => { if (err.status >= 500) { errorMessage('router', err) } res.status(err.status || 500).json({ error: err.message }) }) // Start API server server = app.listen(process.env.PORT || 3000, () => { serverStarted = true const addr = server.address() logMessage('router', `API started at port ${addr.port}`) })