-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkernel.ts
212 lines (184 loc) · 6.29 KB
/
kernel.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import 'reflect-metadata';
import express, { NextFunction, Request, Response } from 'express';
import morgan from 'morgan';
import 'dotenv/config';
import path from 'path';
import fs from 'fs';
import favicon from 'serve-favicon';
import ApiError from './utils/ApiError';
import HttpStatusCode from './helpers/HttpsResponse';
import TestController from './api/controllers/TestController';
import { uploadHelper } from './decorators/FileHandler';
// import db from './models';
import logger from './utils/logger';
import AuthController from './api/controllers/AuthController/auth.controller';
import fileConfig from './config/fileConfig';
import Helper from './helpers';
import globalErrorHandler from './helpers/globalErrorHandler';
process.env.TZ = 'Africa/Lagos';
class Kernel {
app: express.Application;
constructor() {
this.app = express();
this.middlewares();
this.webhooks();
this.mapControllersToRoutes([TestController, AuthController]);
this.errorHandler();
// this.databaseConnection();
if (fileConfig.default === 'local') {
const dir = <string>process.env.UPLOADS_DIR!;
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
}
}
middlewares() {
this.app.set('views', path.join(__dirname, '../views'));
this.app.set('view engine', 'ejs');
this.app.use(express.json());
this.app.use(express.urlencoded({ extended: false }));
this.app.set('PORT', process.env.PORT || 5500);
this.app.set('NODE_ENV', process.env.NODE_ENV);
this.app.use(
favicon(path.join(__dirname, '../public/icon', 'favicon.ico')),
);
this.app.use(express.static(path.join(__dirname, '../public')));
}
webhooks() {}
routes() {
this.app.get('/', (req, res, next) =>
res.status(200).json({
nessage: 'hello',
}),
);
this.app.post(
'/upload',
uploadHelper({
fields: [{ name: 'image', maxCount: 1 }],
validationFunction: Helper.requestFileValidation([
'image/jpeg',
'image/png',
]),
limit: null,
}),
(req, res, next) => {
return res
.status(200)
.json({ files: (<any>req).files.image[0], file: req.file });
},
);
}
errorHandler() {
/**404 routes */
this.app.all('*', (req, res, next) => {
return next(
new ApiError('Route not found', HttpStatusCode.HTTP_NOT_FOUND, {
message:
'The route you are looking for has been moved or does not exist',
}),
);
});
/**global error handler */
this.app.use(globalErrorHandler);
}
//connects server to database
// databaseConnection() {
// (async function () {
// try {
// await db.sequelize.authenticate();
// logger.info('Database Module Connected');
// } catch (error) {
// logger.error('Database connection error: ', error);
// }
// })();
// }
//maps routes to controllers passed in as arguments
mapControllersToRoutes(controllers: any[]) {
//map through controllers
controllers.forEach((controller) => {
//gets base path from @Controller decorator
const basePath = controller.prototype.basePath || '';
//gets routes(@Post, @Get ...) argument from controller class if no route found return an empty array
const routes = controller.prototype.routes || [];
//runs through each route
routes.forEach((route: { path: string; method: string; key: any }) => {
//logs each discovered route from the controller
logger.info(
`[${route.method}] ${basePath}${route.path} to ${controller.name}`,
);
//initialize middlewares
const middleware =
controller.prototype.middleware?.[route.key] ||
controller.prototype.middleware;
//initialize middlewares route guards
const guards =
controller.prototype.guards?.[route.key] || controller.guards;
//create an array to handle the the routes and pass to the express app object
const handlers: any = [];
//checks if guards exists, guards work only function or class prototype level
if (guards) {
const guardArray = Array.isArray(guards) ? guards : [guards];
guardArray.forEach((guard: any) => {
// Check if it's a static method (class constructor)
if (typeof guard.authenticate === 'function') {
handlers.push(
guard.authenticate as (
req: Request,
res: Response,
next: NextFunction,
) => void,
);
} else {
throw new Error(
`Invalid guard in ${controller.name}.${route.key}. The guard must have an 'authenticate' function.`,
);
}
});
}
//checks for middleware and push to handler array
if (middleware) {
handlers.push(
...(Array.isArray(middleware)
? middleware
: middleware !== undefined
? []
: [middleware]),
);
}
if (controller.prototype.hasOwnProperty(route.key)) {
handlers.push(
controller.prototype[route.key].bind(controller.prototype) as (
req: Request,
res: Response,
next: NextFunction,
) => void,
);
} else {
logger.warn(
`Method ${route.key} not found on ${controller.name}, skipping.`,
);
}
// Check if there are any handlers before registering the route to server
if (handlers.length > 0) {
return (this.app as any)[route.method.toLowerCase()](
`${basePath}${route.path}`,
...handlers.map((handler: any) => {
return (req: Request, res: Response, next: NextFunction) => {
return handler(req, res, next);
};
}),
);
} else {
logger.warn(
`No middleware or handler found for ${route.method} ${basePath}${route.path} on ${controller.name}. Skipping.`,
);
}
});
});
}
}
process.on('uncaughtException', (err) => {
logger.error(JSON.stringify(`${err.name}: ${err.message}`));
process.exit(1);
});
export default new Kernel().app;