-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
78 lines (64 loc) · 1.93 KB
/
app.js
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
'use strict';
const express = require('express');
const config = require('./src/config/app.constants.js');
const LoggingMiddleware = require('./src/middleware/LoggingMiddleware');
const ErrorHandler = require('./src/middleware/ErrorHandler');
const routes = require('./src/routes');
const { HTTP_STATUS_CODE } = require('./src/config/http.constants.js');
const connectToDatabase = require('./src/db');
const Logger = require('./src/utils/Logger');
const cors = require('cors');
class AppServer {
constructor() {
this.app = express();
this.loadGlobalConstantVariable();
this.setupMiddleware();
this.setupRoutes();
this.setupErrorHandling();
}
async loadGlobalConstantVariable() {
global.APP_CONFIG = config;
global.HTTP_STATUS_CODE = HTTP_STATUS_CODE;
await connectToDatabase();
}
setupMiddleware() {
// Basic middleware
this.app.use(express.json({ limit: APP_CONFIG.REQUEST_LIMIT }));
this.app.use(express.urlencoded({ extended: true, limit: APP_CONFIG.REQUEST_LIMIT }));
// CORS middleware
this.app.use(cors());
// Custom middleware
this.app.use(LoggingMiddleware.requestLogger);
}
setupRoutes() {
this.app.use('/', routes);
this.app.use((req, res) => {
Logger.log(req.path); // Log the path for debugging
res.status(HTTP_STATUS_CODE.NOT_FOUND).json({
success: false,
message: 'Resource not found',
});
});
}
setupErrorHandling() {
this.app.use(ErrorHandler.handleErrors);
}
start() {
return this.app.listen(APP_CONFIG.PORT, () => {
Logger.info(
'SERVER',
`Application started on port ${APP_CONFIG.PORT} in ${APP_CONFIG.ENVIRONMENT} mode`
);
});
}
getApp() {
return this.app;
}
}
// Create and start server instance if running directly
if (require.main === module) {
const server = new AppServer();
server.start();
}
// Export server class for testing
module.exports = AppServer;