-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
58 lines (45 loc) · 2.6 KB
/
server.js
File metadata and controls
58 lines (45 loc) · 2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
const express = require('express');
const path = require('path');
const config = require('./config');
const logger = require('./utils/logger');
const corsMiddleware = require('./middleware/cors.middleware');
const requestLogger = require('./middleware/logger.middleware');
const errorHandler = require('./middleware/errorHandler.middleware');
const notFound = require('./middleware/notFound.middleware');
const { apiLimiter } = require('./middleware/rateLimit.middleware');
const apiRoutes = require('./routes');
const healthRoutes = require('./routes/health.routes');
const app = express();
// ── Global middleware ──────────────────────────────────────────────────────────
app.use(corsMiddleware);
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(requestLogger);
// ── Health check (no rate limit, no auth) ─────────────────────────────────────
app.use('/health', healthRoutes);
// ── API routes ─────────────────────────────────────────────────────────────────
app.use('/api', apiLimiter, apiRoutes);
// ── Static build (production) ──────────────────────────────────────────────────
app.use(express.static(path.join(__dirname, 'build')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
// ── Error handling (must be last) ──────────────────────────────────────────────
app.use(notFound);
app.use(errorHandler);
// ── Start server ───────────────────────────────────────────────────────────────
const server = app.listen(config.port, () => {
logger.info(`Environment : ${config.env}`);
logger.info(`Server : http://localhost:${config.port}`);
logger.info(`API : http://localhost:${config.port}/api`);
});
server.on('error', (err) => {
if (err.code === 'EADDRINUSE') {
logger.error(`Port ${config.port} is already in use.`);
logger.error('Set a different port via PORT= environment variable.');
process.exit(1);
} else {
throw err;
}
});
module.exports = app;