-
Notifications
You must be signed in to change notification settings - Fork 31
/
app.js
74 lines (66 loc) · 2.31 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
////////////////////////////////////////////////////////
// IMPORTS
////////////////////////////////////////////////////////
import express from 'express';
import morgan from 'morgan';
import helmet from 'helmet';
import compression from 'compression';
import { fileURLToPath } from 'url';
import viewRouter from './routes/viewRoutes.js';
import apiRouter from './routes/apiRoutes.js';
import globalErrorHandler from './controllers/errorController.js';
import AppError from './utils/AppError.js';
////////////////////////////////////////////////////////
// CREATING AND CONFIGURING APP
////////////////////////////////////////////////////////
// 0. CREATING APP
const app = express();
// 1. IMPORTANT MIDDLWARES
app.use(compression()); // compressing responses
app.use(
helmet({
contentSecurityPolicy: {
directives: {
'block-all-mixed-content': null, // deprecated.
'upgrade-insecure-requests': process.env.NO_UPGRADE ? null : [],
},
},
crossOriginEmbedderPolicy: false,
})
); // using sane headers on response
// 2. SETTING VIEW ENGINE AND PATH TO STATIC ASSETS
app.set('view engine', 'pug');
const pathToViews = fileURLToPath(
new URL('./views/pug/pages', import.meta.url)
);
app.set('views', pathToViews);
const pathToPublicDirectory = fileURLToPath(
new URL('./public', import.meta.url)
);
app.use(
express.static(pathToPublicDirectory, {
maxAge: process.env.CACHE_PERIOD || '1h',
})
);
// 3. MISC MIDDLEWARES
if (process.env.NODE_ENV === 'development') app.use(morgan('dev')); // for logging during development
// middleware to add baseUrl to req object
app.use((req, res, next) => {
req.urlObj = new URL(req.originalUrl, `${req.protocol}://${req.get('host')}`);
next();
});
// 4. MIDDLWARES FOR ROUTES
app.use('/', viewRouter);
app.use('/api/v1/', apiRouter);
////////////////////////////////////////////////////////
// HANDLING ERRORS
////////////////////////////////////////////////////////
// for all other routes, throwing error
app.all('*', (req, res, next) => {
next(new AppError(`this route(${req.originalUrl}) doesn't exist`, 404));
});
app.use(globalErrorHandler);
////////////////////////////////////////////////////////
// EXPORTS
////////////////////////////////////////////////////////
export default app;