-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
179 lines (158 loc) · 6.79 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
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
'use strict'
const url = require('url')
const http = require('http')
const https = require('https')
const express = require('express')
const app = express()
// using CJS in ESM sibling-module.js is a CommonJS module
// import { createRequire } from 'module'
// const require = createRequire(import.meta.url)
// const siblingModule = require('./sibling-module')
const { sleep } = require('esm')(module)('@es-labs/esm/sleep')
require('@es-labs/node/express/init')()
// setup graceful exit
const handleExitSignal = async (signal) => await cleanup(`Signal ${signal}`, 0) // NOSONAR
const handleExitException = async (err, origin) => await cleanup(`Uncaught Exception. error: ${err?.stack || err} origin: ${origin}`, 1) // NOSONAR
const handleExitRejection = async (reason, promise) => await cleanup(`Unhandled Rejection. reason: ${reason?.stack || reason}`, 1) // NOSONAR
process.on('SIGINT', handleExitSignal)
process.on('SIGTERM', handleExitSignal)
process.on('SIGQUIT', handleExitSignal)
process.on('uncaughtException', handleExitException)
process.on('unhandledRejection', handleExitRejection)
const { HTTPS_PRIVATE_KEY, HTTPS_CERTIFICATE } = process.env
const https_opts = {}
if (HTTPS_CERTIFICATE) {
https_opts.key = HTTPS_PRIVATE_KEY
https_opts.cert = HTTPS_CERTIFICATE
// UNUSED AT THE MOMENT
// passphrase = (fs.readFileSync('passphrase.txt')).toString()
// pfx = fs.readFileSync('8ab20f7b-51b9-4c09-a2e0-1918bb9fb37f.pfx')
// ca = fs.readFileSync('ca.cert')
}
const server = HTTPS_CERTIFICATE ? https.createServer(https_opts, app) : http.createServer(app)
// USERLAND - Add APM tool
require('@es-labs/node/express/preRoute')(app, express)
const graphqlWsServer = require('@es-labs/node/express/graphql')(app, server)
const services = require('@es-labs/node/services')
const authService = require('@es-labs/node/auth')
// CLEANUP
const cleanup = async (message, exitCode = 0, coreDump = false, timeOutMs = 1000) => {
console.log(message)
console.log(`
node win - cannot see messages
node bash - can see messages
`)
if (server) {
server.close(async () => {
try {
await graphqlWsServer?.close()
await services.stop()
// or should process.exit be placed here?
} catch (e) {
console.error(e)
}
})
}
console.log('cleaning up and awaiting exit...')
await sleep(timeOutMs) // from here on... does not get called on uncaught exception crash
console.log('exiting') // require('fs').writeSync(process.stderr.fd, `bbbbbbbbbbbb`)
return coreDump ? process.abort : process.exit(exitCode)
// setTimeout(() => console.log('exiting'), timeOutMs).unref()
}
// SERVICES
services.start()
try {
authService.setup(services.get('keyv'), services.get('knex1')) // setup authorization
} catch (e) {
console.log(e)
}
// ROUTES
// 1. asyncWrapper
// https://strongloop.com/strongblog/async-error-handling-expressjs-es7-promises-generators/#usinges7asyncawait
// https://gist.github.com/Hiswe/fe83c97d1c7c8eee9557939d1b9bc086
// Caveats:
// 1. You must have all your asynchronous code return promises (except emitters). Raw callbacks simply don’t have the facilities for this to work.
// 2. Event emitters (like streams) can still cause uncaught exceptions. So make sure you are handling the error event properly e.g. stream.on('error', next).pipe(res)
// DOs:
// DO use throw, and try/catch when needed
// DO use custom error classes like BadRequestError as it makes sorting errors out easier
// const asyncWrapper = fn => (...args) => fn(...args).catch(args[2])
// module.exports = asyncWrapper
// USAGE:
// const wrap = require('./<path-to>/asyncWrapper')
// app.get('/', wrap(async (req, res) => { ... }))
// replaced by - express-async-errors, will be native in express 5
// global.asyncWrapper = fn => (...args) => fn(...args).catch(args[2]) // proceed to error handler
// https://github.com/express-promise-router/express-promise-router
// https://github.com/davidbanham/express-async-errors
// https://stackoverflow.com/questions/44327291/express-js-wrap-every-middleware-route-in-decorator
// https://github.com/expressjs/express/issues/4256
// https://github.com/expressjs/express/issues/3748
// https://stackoverflow.com/questions/44327291/express-js-wrap-every-middleware-route-in-decorator
const Layer = require('express/lib/router/layer')
const handle_request = Layer.prototype.handle_request
Layer.prototype.handle_request = function(req, res, next) {
if (!this.isWrapped && this.method) {
let handle = this.handle
this.handle = function(req, res, next) { // this is basically your wrapper
// console.log(req.url)
const rv = handle.apply(this, arguments)
if (rv instanceof Promise) rv.then(result => result).catch(error => next(error))
else return rv
}
this.isWrapped = true
}
return handle_request.apply(this, arguments)
}
try {
console.log('Start App Routes Load')
require('./apps/apploader')(app) // add your APIs here
console.log('Start Common Routes Load')
require('./router')(app); // common routes
console.log('Start Fallback Routes Load')
app.use('/api/**', (req, res) =>
res.status(404).json({ error: 'Not Found' })
)
console.log('Routes Load Completed')
} catch (e) {
console.log('Route loading exception', e.toString())
}
// END ROUTES
// OpenAPI
const { OPENAPI_OPTIONS } = process.env
const openApiOptions = JSON.parse(OPENAPI_OPTIONS || null)
if (openApiOptions) {
openApiOptions.baseDir = __dirname
const expressJSDocSwagger = require('express-jsdoc-swagger')
expressJSDocSwagger(app)(openApiOptions)
}
// websockets
server.on('upgrade', (request, socket, head) => {
const pathname = url.parse(request.url).pathname
if (pathname === '/subscriptions') {
// upgrade the graphql server
graphqlWsServer.handleUpgrade(request, socket, head, (ws) => {
graphqlWsServer.emit('connection', ws, request)
})
}
console.log('upgrade event')
})
require('@es-labs/node/express/postRoute')(app, express)
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
// 'Bad Request': 400, 'Unauthorized': 401, 'Forbidden': 403, 'Not Found': 404, 'Conflict': 409, 'Unprocessable Entity': 422, 'Internal Server Error': 500,
app.use((error, req, res, next) => {
// error middleware - 200s should not reach here
// console.log('typeof error', error instanceof Error)
console.log('error middleware', error)
let message = 'Unknown Error'
if (error.message) {
// console.log('Error Object', error.name, error.name, error.stack)
message = (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'dev') ? error.stack : error.message
} else if (typeof error === 'string') {
message = error
} else if (error?.toString) {
message = error.toString()
}
return !res.headersSent ? res.status(500).json({ message }) : next()
})
module.exports = { server }