-
Notifications
You must be signed in to change notification settings - Fork 1
/
core.js
124 lines (108 loc) · 3.4 KB
/
core.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
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
const fs = require('fs')
const path = require('path')
const process = require('process')
const debug = require('debug')('mvc-webapp:core')
const express = require('express')
const session = require('express-session')
const Redis = require('redis')
const logger = require('morgan')
const RedisStore = require('connect-redis').default
const createApp = function (options) {
const app = express()
// View engine setup
if (options.viewEngine) {
const viewsPath = path.join(options.applicationRoot, 'application/views')
app.set('views', viewsPath)
app.set('view engine', options.viewEngine)
}
return app
}
exports.create = async function (options) {
debug('Application Root:', options.applicationRoot)
const app = createApp(options)
app.set('port', options.listenPort)
// Engine options
app.use(logger(options.loggerFormat || 'common'))
app.use(express.json())
app.use(express.urlencoded({extended: false}))
app.use(express.static(path.join(options.applicationRoot, 'application/public')))
// Trust Proxy
if (options.trustProxy) {
app.enable('trust proxy')
debug('Trusting Proxy.')
}
// Session Storage
if (options.sessionRedisUrl) {
const redisClient = await Redis.createClient({
url: process.env.REDIS_URL
})
.on('error', error => debug('Redis Fail', error))
.connect()
const redisStore = new RedisStore({
client: redisClient,
prefix: 'session:'
})
debug('Setting up for Redis session management.')
app.use(session({
secret: options.sessionSecret,
resave: false,
saveUninitialized: false,
store: redisStore,
}))
}
// Ensure secure connection in production
if (options.redirectSecure) {
app.use((request, response, next) => {
if (options.redirectSecure && !request.secure && request.get('x-forwarded-proto') !== 'https' && process.env.NODE_ENV === 'production') {
return response.redirect('https://' + request.get('host') + request.url)
}
next()
})
}
// Cross Origin Resource Sharing
if (options.allowCORS) {
app.options('/*', (request, response, _) => {
response.header('Access-Control-Allow-Origin', '*')
response.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
response.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, X-Api-Key')
response.sendStatus(200)
})
}
// Load controllers into Express middleware
const controllersPath = path.join(options.applicationRoot, 'application/controllers')
for (const file of fs.readdirSync(controllersPath)
.filter(file => path.extname(file) === '.js')) {
const filepath = path.parse(file)
const controller = require(path.join(controllersPath, filepath.name))
const sitepath = '/' + ((filepath.name === 'index') ? '' : filepath.name)
const subapp = createApp(options)
debug('Loading controller on path:', sitepath)
app.use(sitepath, controller.actions(subapp))
}
// File Not Found
app.use((request, response, next) => {
if (options.notfoundMiddleware) {
options.notfoundMiddleware(request, response, next)
} else {
response.status(404).json({
code: 404,
message: 'File Not Found'
})
}
})
// Error handler
app.use((error, request, response, next) => {
if (response.headersSent) {
return next(error)
}
if (options.errorMiddleware) {
options.errorMiddleware(error, request, response, next)
} else {
response.status(500).json({
code: 500,
message: error
})
}
})
return app
}