-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.ts
652 lines (560 loc) · 21.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
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
// Expresser: app.ts
import EventEmitter = require("eventemitter3")
import express = require("express")
import {Http2SecureServer, Http2Server} from "http2"
/** @hidden */
const _ = require("lodash")
/** @hidden */
const fs = require("fs")
/** @hidden */
const http = require("http")
/** @hidden */
const https = require("https")
/** @hidden */
const jaul = require("jaul")
/** @hidden */
const logger = require("anyhow")
/** @hidden */
const path = require("path")
/** @hidden */
const settings = require("setmeup").settings
/** Middleware definitions to be be passed on app [[init]]. */
interface MiddlewareDefs {
/** Single or array of middlewares to be prepended. */
prepend: any | any[]
/** Single or array of middlewares to be appended. */
append: any | any[]
}
/** Main App class. */
class App {
private static _instance: App
/** @hidden */
static get Instance() {
return this._instance || (this._instance = new this())
}
/** Returns a new fresh instance of the App module. */
newInstance(): App {
return new App()
}
/** Default App constructor. */
constructor() {
if (!logger.isReady) {
/* istanbul ignore next */
logger.setup()
}
// Set preprocessor, if not set yet.
if (!logger.preprocessor) {
logger.preprocessor = require("./logger").clean
}
logger.errorStack = settings.logger.errorStack
}
// PROPERTIES
// --------------------------------------------------------------------------
/** Express application. */
expressApp: express.Application
/** The underlying HTTP(S) server. */
server: any
/** Event emitter. */
events: EventEmitter = new EventEmitter()
// EVENTS
// --------------------------------------------------------------------------
/**
* Bind callback to event. Shortcut to `events.on()`.
* @param eventName The name of the event.
* @param callback Callback function.
*/
on(eventName: string, callback: EventEmitter.ListenerFn): void {
this.events.on(eventName, callback)
}
/**
* Bind callback to event that will be triggered only once. Shortcut to `events.once()`.
* @param eventName The name of the event.
* @param callback Callback function.
*/
once(eventName: string, callback: EventEmitter.ListenerFn): void {
this.events.on(eventName, callback)
}
/**
* Unbind callback from event. Shortcut to `events.off()`.
* @param eventName The name of the event.
* @param callback Callback function.
*/
off(eventName: string, callback: EventEmitter.ListenerFn): void {
this.events.off(eventName, callback)
}
// MAIN METHODS
// --------------------------------------------------------------------------
/**
* Init the app module and start the HTTP(S) server.
* @param middlewares List of middlewares to be appended / prepended.
* @event init
*/
init(middlewares?: MiddlewareDefs) {
let mw
// Create express v4 app.
this.expressApp = express()
middlewares = middlewares || {append: [], prepend: []}
// Make sure passed middlewares are array based.
if (middlewares.prepend && !_.isArray(middlewares.prepend)) {
middlewares.prepend = [middlewares.prepend]
}
if (middlewares.append && !_.isArray(middlewares.append)) {
middlewares.append = [middlewares.append]
}
// Prepend middlewares?
if (middlewares.prepend && middlewares.prepend.length > 0) {
for (mw of middlewares.prepend) {
if (mw) {
this.expressApp.use(mw)
logger.debug("App.init", "Prepended middleware")
}
}
}
// Trust proxy (mainly for secure cookies)?
this.expressApp.set("trust proxy", settings.app.trustProxy)
// Default view path.
this.expressApp.set("views", settings.app.viewPath)
// Set view options, use Pug for HTML templates.
if (settings.app.viewEngine) {
this.expressApp.set("view engine", settings.app.viewEngine)
this.expressApp.set("view options", settings.app.viewOptions)
}
// Use body parser?
if (settings.app.bodyParser.enabled) {
try {
const midBodyParser = require("body-parser")
this.expressApp.use(midBodyParser.json({extended: settings.app.bodyParser.extended, limit: settings.app.bodyParser.limit}))
this.expressApp.use(midBodyParser.urlencoded({extended: settings.app.bodyParser.extended, limit: settings.app.bodyParser.limit}))
} catch (ex) {
/* istanbul ignore next */
logger.warn("App.init", "Can't load 'body-parser' module.")
}
}
// Cookies enabled?
if (settings.app.cookie.enabled) {
try {
const midCookieParser = require("cookie-parser")
this.expressApp.use(midCookieParser(settings.app.secret))
} catch (ex) {
/* istanbul ignore next */
ex.friendlyMessage = "Can't load 'cookie-parser' module."
/* istanbul ignore next */
logger.error("App.init", ex)
}
}
// Session enabled?
if (settings.app.session.enabled) {
try {
const midSession = require("express-session")
const memoryStore = require("memorystore")(midSession)
this.expressApp.use(
midSession({
store: new memoryStore({checkPeriod: settings.app.session.checkPeriod}),
proxy: settings.app.session.proxy,
resave: settings.app.session.resave,
saveUninitialized: settings.app.session.saveUninitialized,
secret: settings.app.secret,
ttl: settings.app.session.maxAge * 1000,
cookie: {
secure: settings.app.session.secure,
httpOnly: settings.app.session.httpOnly,
maxAge: settings.app.session.maxAge * 1000
}
})
)
} catch (ex) {
/* istanbul ignore next */
ex.friendlyMessage = "Can't load 'express-session' and 'memorystore' modules."
/* istanbul ignore next */
logger.error("App.init", ex)
}
}
// Use HTTP compression only if enabled on settings.
if (settings.app.compression.enabled) {
try {
const midCompression = require("compression")
this.expressApp.use(midCompression())
} catch (ex) {
/* istanbul ignore next */
ex.friendlyMessage = "Can't load 'compression' module."
/* istanbul ignore next */
logger.error("App.init", ex)
}
}
// Use Express static routing.
if (settings.app.publicPath) {
this.expressApp.use(express.static(settings.app.publicPath))
}
// Append middlewares?
if (middlewares.append && middlewares.append.length > 0) {
for (mw of middlewares.append) {
if (mw) {
this.expressApp.use(mw)
logger.debug("App.init", "Appended middleware")
}
}
}
// Log all requests if debug is true.
if (settings.general.debug) {
this.expressApp.use(function(req, res, next) {
const {method} = req
const {url} = req
const ip = jaul.network.getClientIP(req)
const msg = `Request from ${ip}`
if (res) {
logger.debug("App", msg, method, url)
}
if (next) {
next()
}
return url
})
}
// Dispatch init event, and start the server.
this.events.emit("init")
this.start()
}
/**
* Start the HTTP(S) server.
* @returns The HTTP(S) server created by Express.
* @event start
*/
start(): Http2Server | Http2SecureServer {
if (this.server) {
logger.warn("App.start", "Server is already running, abort start.")
return this.server
}
let serverRef
if (settings.app.ssl.enabled && settings.app.ssl.keyFile && settings.app.ssl.certFile) {
const sslKeyFile = jaul.io.getFilePath(settings.app.ssl.keyFile)
const sslCertFile = jaul.io.getFilePath(settings.app.ssl.certFile)
// Certificate files were found? Proceed, otherwise alert the user and throw an error.
if (sslKeyFile && sslCertFile) {
const sslKey = fs.readFileSync(sslKeyFile, {encoding: settings.general.encoding})
const sslCert = fs.readFileSync(sslCertFile, {encoding: settings.general.encoding})
const sslOptions = {key: sslKey, cert: sslCert}
serverRef = https.createServer(sslOptions, this.expressApp)
} else {
throw new Error("Invalid certificate filename, please check paths defined on settings.app.ssl.")
}
} else {
serverRef = http.createServer(this.expressApp)
}
// Expose the web server.
this.server = serverRef
let listenCb = () => {
if (settings.app.ip) {
logger.info("App.start", settings.app.title, `Listening on ${settings.app.ip} port ${settings.app.port}`, `URL ${settings.app.url}`)
} else {
logger.info("App.start", settings.app.title, `Listening on port ${settings.app.port}`, `URL ${settings.app.url}`)
}
}
/* istanbul ignore next */
let listenError = err => {
/* istanbul ignore next */
logger.error("App.start", "Can't start", err)
}
// Start the app!
if (settings.app.ip) {
serverRef.listen(settings.app.port, settings.app.ip, listenCb).on("error", listenError)
serverRef.setTimeout(settings.app.timeout)
} else {
serverRef.listen(settings.app.port, listenCb).on("error", listenError)
serverRef.setTimeout(settings.app.timeout, listenCb)
}
// Emit start event and return HTTP(S) server.
this.events.emit("start")
return this.server
}
/**
* Kill the underlying HTTP(S) server(s).
* @event kill
*/
kill(): void {
if (!this.server) {
logger.warn("App.kill", "Server was not running")
return
}
try {
this.server.close()
this.server = null
this.events.emit("kill")
} catch (ex) {
/* istanbul ignore next */
logger.error("App.kill", ex)
}
}
// BRIDGED METHODS
// --------------------------------------------------------------------------
/**
* Shortcut to express ".all()".
* @param reqPath The path for which the middleware function is invoked.
* @param callbacks Single, array or series of middlewares.
*/
all(reqPath: string | RegExp | any[], ...callbacks: any[]) {
logger.debug("App.all", reqPath, ...callbacks)
return this.expressApp.all.apply(this.expressApp, arguments)
}
/**
* Shortcut to express ".get()".
* @param reqPath The path for which the middleware function is invoked.
* @param callbacks Single, array or series of middlewares.
*/
get(reqPath: string | RegExp | any[], ...callbacks: any[]) {
logger.debug("App.get", reqPath, ...callbacks)
return this.expressApp.get.apply(this.expressApp, arguments)
}
/**
* Shortcut to express ".post()".
* @param reqPath The path for which the middleware function is invoked.
* @param callbacks Single, array or series of middlewares.
*/
post(reqPath: string | RegExp | any[], ...callbacks: any[]) {
logger.debug("App.post", reqPath, ...callbacks)
return this.expressApp.post.apply(this.expressApp, arguments)
}
/**
* Shortcut to express ".put()".
* @param reqPath The path for which the middleware function is invoked.
* @param callbacks Single, array or series of middlewares.
*/
put(reqPath: string | RegExp | any[], ...callbacks: any[]) {
logger.debug("App.put", reqPath, ...callbacks)
return this.expressApp.put.apply(this.expressApp, arguments)
}
/**
* Shortcut to express ".patch()".
* @param reqPath The path for which the middleware function is invoked.
* @param callbacks Single, array or series of middlewares.
*/
patch(reqPath: string | RegExp | any[], ...callbacks: any[]) {
logger.debug("App.patch", reqPath, ...callbacks)
return this.expressApp.patch.apply(this.expressApp, arguments)
}
/**
* Shortcut to express ".delete()".
* @param reqPath The path for which the middleware function is invoked.
* @param callbacks Single, array or series of middlewares.
*/
delete(reqPath: string | RegExp | any[], ...callbacks: any[]) {
logger.debug("App.delete", reqPath, ...callbacks)
return this.expressApp.delete.apply(this.expressApp, arguments)
}
/**
* Shortcut to express ".use()".
* @param reqPath The path for which the middleware function is invoked.
* @param callbacks Single, array or series of middlewares.
*/
use(reqPath?: string, ...callbacks: any[]) {
logger.debug("App.use", reqPath, ...callbacks)
return this.expressApp.use.apply(this.expressApp, arguments)
}
/**
* Shortcut to express ".route()".
* @param reqPath The path of the desired route.
* @returns An instance of a single route for the specified path.
*/
route(reqPath: string): express.IRoute {
logger.debug("App.route", reqPath)
return this.expressApp.route.apply(this.expressApp, arguments)
}
// RENDERING METHODS
// --------------------------------------------------------------------------
/**
* Render a view and send to the client. The view engine depends on the settings defined.
* @param req The Express request object.
* @param res The Express response object.
* @param view The view filename.
* @param options Options passed to the view, optional.
* @event renderView
*/
renderView = (req: express.Request, res: express.Response, view: string, options?: any) => {
logger.debug("App.renderView", req.originalUrl, view, options)
try {
if (!options) {
options = {}
}
if (options.title == null) {
options.title = settings.app.title
}
// Send rendered view to client.
res.render(view, options)
} catch (ex) {
/* istanbul ignore next */
logger.error("App.renderView", view, ex)
/* istanbul ignore next */
this.renderError(req, res, ex)
}
if (settings.app.events.render) {
this.events.emit("renderView", req, res, view, options)
}
}
/**
* Sends pure text to the client.
* @param req The Express request object.
* @param res The Express response object.
* @param text The text to be rendered, mandatory.
* @event renderText
*/
renderText = (req: express.Request, res: express.Response, text: any) => {
logger.debug("App.renderText", req.originalUrl, text)
try {
if (text == null) {
logger.debug("App.renderText", "Called with empty text parameter")
text = ""
} else if (!_.isString(text)) {
text = text.toString()
}
res.setHeader("content-type", "text/plain")
res.send(text)
} catch (ex) {
/* istanbul ignore next */
logger.error("App.renderText", text, ex)
/* istanbul ignore next */
this.renderError(req, res, ex)
}
if (settings.app.events.render) {
this.events.emit("renderText", req, res, text)
}
}
/**
* Render response as JSON data and send to the client.
* @param req The Express request object.
* @param res The Express response object.
* @param data The JSON data to be sent.
* @event renderJson
*/
renderJson = (req: express.Request, res: express.Response, data: any) => {
logger.debug("App.renderJson", req.originalUrl, data)
if (_.isString(data)) {
try {
data = JSON.parse(data)
} catch (ex) {
logger.error("App.renderJson", ex)
return this.renderError(req, res, ex, 500)
}
}
// Remove methods from JSON before rendering.
var cleanJson = function(obj, depth) {
if (depth >= settings.logger.maxDepth) {
return
}
if (_.isArray(obj)) {
return Array.from(obj).map(i => cleanJson(i, depth + 1))
} else if (_.isObject(obj)) {
return (() => {
const result = []
for (let k in obj) {
const v = obj[k]
if (_.isFunction(v)) {
result.push(delete obj[k])
} else {
result.push(cleanJson(v, depth + 1))
}
}
return result
})()
}
}
cleanJson(data, 0)
// Add Access-Control-Allow-Origin if set.
if (settings.app.allowOriginHeader) {
res.setHeader("Access-Control-Allow-Origin", settings.app.allowOriginHeader)
}
// Send JSON response.
res.json(data)
if (settings.app.events.render) {
this.events.emit("renderJson", req, res, data)
}
}
/**
* Render an image from the speficied file, and send to the client.
* @param req The Express request object.
* @param res The Express response object.
* @param filename The full path to the image file.
* @param options Options passed to the image renderer, for example the "mimetype".
* @event renderImage
*/
renderImage = (req: express.Request, res: express.Response, filename: string, options?: any) => {
logger.debug("App.renderImage", req.originalUrl, filename, options)
let mimetype = options ? options.mimetype : null
// Try to figure out the mime type in case it wasn't passed along the options.
if (!mimetype) {
let extname = path
.extname(filename)
.toLowerCase()
.replace(".", "")
if (extname == "jpg") {
extname = "jpeg"
}
mimetype = `image/${extname}`
}
// Send image to client.
res.type(mimetype)
res.sendFile(filename)
if (settings.app.events.render) {
this.events.emit("renderImage", req, res, filename, options)
}
}
/**
* Sends error response as JSON.
* @param req The Express request object.
* @param res The Express response object.
* @param error The error object or message to be sent to the client.
* @param status The response status code, optional, default is 500.
* @event renderError
*/
renderError = (req: express.Request, res: express.Response, error: any, status?: number | string) => {
let message
logger.debug("App.renderError", req.originalUrl, status, error)
/* istanbul ignore next */
if (typeof error == "undefined" || error == null) {
error = "Unknown error"
logger.warn("App.renderError", "Called with null error")
}
// Status default statuses.
if (status == null) {
status = error.statusCode ? error.statusCode : 500
} else if (status === "ETIMEDOUT") {
status = 408
}
try {
// Error inside another .error property?
if (error.error && !error.message && !error.error_description && !error.reason) {
error = error.error
}
if (_.isString(error)) {
message = error
} else {
message = {}
message.message = error.message || error.error_description || error.description
// No message found? Just use the default .toString() then.
/* istanbul ignore next */
if (!message.message) {
message = error.toString()
}
if (error.friendlyMessage) {
message.friendlyMessage = error.friendlyMessage
}
if (error.reason) {
message.reason = error.reason
}
if (error.code) {
message.code = error.code
} else if (error.status) {
message.code = error.status
}
}
} catch (ex) {
/* istanbul ignore next */
logger.error("App.renderError", ex)
}
// Send error JSON to client.
res.status(status as number).json({error: message, url: req.originalUrl})
if (settings.app.events.render) {
this.events.emit("renderError", req, res, error, status)
}
}
}
// Exports...
export = App.Instance