This repository was archived by the owner on Mar 8, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
60 lines (56 loc) · 1.58 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
// ExpressJS dependencies
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const chalk = require('chalk');
const router = require('./src/api/router');
const { handleError } = require('./src/common/helpers/errorHandler');
// ExpressJS application
const app = express();
require('dotenv').config();
// ExpressJS middleware
if (app.get('env') !== 'test') {
app.use(logger('dev'));
}
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Router configuration
router.forEach((route) => {
if (app.get('env') !== 'test') {
console.log(
`${chalk.green('✓')} ${chalk.bold.blue(
route.method.toUpperCase()
)}: ${chalk.blue(route.path)} configured and setup.`
);
}
app[route.method](`/v1${route.path}`, ...route.handlers);
});
// 404 error handler
app.use((req, res) =>
res.status(404).json({
status: 'error',
code: 404,
message: `${req.url} not found`,
})
);
// Error handler
app.use((err, req, res, _next) => {
handleError(err, res);
});
// Initialize ExpressJS app
app.set('port', process.env.PORT || 3000);
const server = app.listen(app.get('port'), () => {
if (app.get('env') !== 'test') {
console.log(
`${chalk.green('✓')} App is running at http://localhost:${app.get(
'port'
)} in ${chalk.yellow(app.get('env'))} mode`
);
console.log('Press CTRL-C to stop\n');
}
});
// Export app instance
module.exports = server;