-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathapp.ts
102 lines (88 loc) · 2.7 KB
/
app.ts
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import compression from 'compression';
import cookieParser from 'cookie-parser';
import cors from 'cors';
import express from 'express';
import helmet from 'helmet';
import hpp from 'hpp';
import morgan from 'morgan';
import { connect, set, disconnect } from 'mongoose';
import swaggerJSDoc from 'swagger-jsdoc';
import swaggerUi from 'swagger-ui-express';
import { NODE_ENV, PORT, LOG_FORMAT, ORIGIN, CREDENTIALS } from '@config';
import { dbConnection } from '@databases';
import { Routes } from '@interfaces/routes.interface';
import errorMiddleware from '@middlewares/error.middleware';
import { logger, stream } from '@utils/logger';
class App {
public app: express.Application;
public env: string;
public port: string | number;
constructor(routes: Routes[]) {
this.app = express();
this.env = NODE_ENV || 'development';
this.port = PORT || 3000;
this.connectToDatabase();
this.initializeMiddlewares();
this.initializeRoutes(routes);
this.initializeSwagger();
this.initializeErrorHandling();
}
public listen() {
this.app.listen(this.port, () => {
logger.info(`=================================`);
logger.info(`======= ENV: ${this.env} =======`);
logger.info(`🚀 App listening on the port ${this.port}`);
logger.info(`=================================`);
});
}
public async closeDatabaseConnection(): Promise<void> {
try {
await disconnect();
console.log('Disconnected from MongoDB');
} catch (error) {
console.error('Error closing database connection:', error);
}
}
public getServer() {
return this.app;
}
private async connectToDatabase() {
if (this.env !== 'production') {
set('debug', true);
}
await connect(dbConnection.url);
}
private initializeMiddlewares() {
this.app.use(morgan(LOG_FORMAT, { stream }));
this.app.use(cors({ origin: ORIGIN, credentials: CREDENTIALS }));
this.app.use(hpp());
this.app.use(helmet());
this.app.use(compression());
this.app.use(express.json());
this.app.use(express.urlencoded({ extended: true }));
this.app.use(cookieParser());
}
private initializeRoutes(routes: Routes[]) {
routes.forEach(route => {
this.app.use('/', route.router);
});
}
private initializeSwagger() {
const options = {
swaggerDefinition: {
info: {
title: 'REST API',
version: '1.0.0',
description: 'Example docs',
},
},
apis: ['swagger.yaml'],
};
const specs = swaggerJSDoc(options);
this.app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specs));
}
private initializeErrorHandling() {
this.app.use(errorMiddleware);
}
}
export default App;