97 lines
2.4 KiB
JavaScript
97 lines
2.4 KiB
JavaScript
|
import { Flaska, QueryHandler, JsonHandler, FormidableHandler } from 'flaska'
|
||
|
import StaticRoutes from './static_routes.mjs'
|
||
|
import IngestRoutes from './ingest.mjs'
|
||
|
|
||
|
export default class Server {
|
||
|
constructor(http, port, core, opts = {}) {
|
||
|
Object.assign(this, opts)
|
||
|
this.http = http
|
||
|
this.port = port
|
||
|
this.core = core
|
||
|
this.pool = null
|
||
|
|
||
|
this.flaskaOptions = {
|
||
|
log: this.core.log,
|
||
|
}
|
||
|
this.jsonHandler = JsonHandler
|
||
|
this.routes = {
|
||
|
static: new StaticRoutes(),
|
||
|
ingest: new IngestRoutes(),
|
||
|
}
|
||
|
}
|
||
|
|
||
|
runCreateServer() {
|
||
|
// Create our server
|
||
|
this.flaska = new Flaska(this.flaskaOptions, this.http)
|
||
|
|
||
|
// configure our server
|
||
|
if (process.env.NODE_ENV !== 'production') {
|
||
|
this.flaska.devMode()
|
||
|
}
|
||
|
|
||
|
this.flaska.before(function(ctx) {
|
||
|
ctx.state.started = new Date().getTime()
|
||
|
ctx.req.ip = ctx.req.headers['x-forwarded-for'] || ctx.req.connection.remoteAddress
|
||
|
ctx.log = ctx.log.child({
|
||
|
id: Math.random().toString(36).substring(2, 14),
|
||
|
})
|
||
|
}.bind(this))
|
||
|
this.flaska.before(QueryHandler())
|
||
|
|
||
|
let healthChecks = 0
|
||
|
let healthCollectLimit = 60 * 60 * 12
|
||
|
|
||
|
this.flaska.after(function(ctx) {
|
||
|
let ended = new Date().getTime()
|
||
|
var requestTime = ended - ctx.state.started
|
||
|
|
||
|
let status = ''
|
||
|
let level = 'info'
|
||
|
if (ctx.status >= 400) {
|
||
|
status = ctx.status + ' '
|
||
|
level = 'warn'
|
||
|
}
|
||
|
if (ctx.status >= 500) {
|
||
|
level = 'error'
|
||
|
}
|
||
|
|
||
|
if (ctx.url === '/health' || ctx.url === '/api/health') {
|
||
|
healthChecks++
|
||
|
if (healthChecks >= healthCollectLimit) {
|
||
|
ctx.log[level]({
|
||
|
duration: Math.round(ended),
|
||
|
status: ctx.status,
|
||
|
}, `<-- ${status}${ctx.method} ${ctx.url} {has happened ${healthChecks} times}`)
|
||
|
healthChecks = 0
|
||
|
}
|
||
|
return
|
||
|
}
|
||
|
|
||
|
ctx.log[level]({
|
||
|
duration: requestTime,
|
||
|
status: ctx.status,
|
||
|
ip: ctx.req.ip,
|
||
|
}, (ctx.aborted ? '-->' : '<--') + ` ${status}${ctx.method} ${ctx.url}`)
|
||
|
})
|
||
|
}
|
||
|
|
||
|
runRegisterRoutes() {
|
||
|
let keys = Object.keys(this.routes)
|
||
|
for (let key of keys) {
|
||
|
this.routes[key].register(this)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
runStartListen() {
|
||
|
return this.flaska.listenAsync(this.port).then(() => {
|
||
|
this.core.log.info('Server is listening on port ' + this.port)
|
||
|
})
|
||
|
}
|
||
|
|
||
|
run() {
|
||
|
this.runCreateServer()
|
||
|
this.runRegisterRoutes()
|
||
|
return this.runStartListen()
|
||
|
}
|
||
|
}
|