express-api-base/router/index.js

66 lines
1.5 KiB
JavaScript
Raw Permalink Normal View History

2024-06-28 09:20:46 +00:00
'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}`)
})