service-core/dev/api/server.mjs

82 lines
2.2 KiB
JavaScript
Raw Normal View History

2020-09-01 17:31:38 +00:00
import http from 'http'
import path from 'path'
import { fileURLToPath } from 'url'
import socket from 'socket.io-serveronly'
import nStatic from 'node-static'
2020-09-07 00:47:53 +00:00
import coremonitor from './core/coremonitor.mjs'
2020-09-01 17:31:38 +00:00
import onConnection from './routerio.mjs'
2020-09-07 00:47:53 +00:00
export function run(config, db, log, core) {
2020-09-01 17:31:38 +00:00
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const staticRoot = path.join(__dirname,'../public')
const fileServer = new nStatic.Server(staticRoot)
const server = http.createServer(function (req, res) {
const child = log.child({})
const d1 = new Date().getTime()
let finishedRequest = false
var done = function () {
if (finishedRequest) return
finishedRequest = true
if (req.url === '/main.css.map') return
var requestTime = new Date().getTime() - d1
let level = 'debug'
if (res.statusCode >= 400) {
level = 'warn'
}
if (res.statusCode >= 500) {
level = 'error'
}
let status = ''
if (res.statusCode >= 400) {
status = res.statusCode + ' '
}
child[level]({
duration: requestTime,
status: res.statusCode,
}, `<-- ${status}${req.method} ${req.url}`)
}
res.addListener('finish', done);
res.addListener('close', done);
req.addListener('end', function () {
if (req.url === '/') {
res.writeHead(302, { Location: '/index.html' })
return res.end()
}
fileServer.serve(req, res, function (err) {
if (err) {
if (err.status !== 404) {
log.error(err, req.url);
}
res.writeHead(err.status, err.headers);
res.end(err.message);
}
});
}).resume()
})
const io = new socket(server)
2020-09-07 00:47:53 +00:00
io.on('connection', onConnection.bind(this, io, config, db, log, core))
2020-09-01 17:31:38 +00:00
2020-09-07 00:47:53 +00:00
coremonitor(io, config, db, log, core)
2020-09-01 17:31:38 +00:00
2020-09-07 00:47:53 +00:00
server.listen(config.managePort, '0.0.0.0', function(err) {
2020-09-01 17:31:38 +00:00
if (err) {
log.fatal(err)
2020-09-07 00:47:53 +00:00
log.event.error('Error starting server: ' + err.message)
2020-09-01 17:31:38 +00:00
return process.exit(2)
}
2020-09-07 00:47:53 +00:00
log.event.info(`Server is listening on ${config.managePort} serving files on ${staticRoot}`)
log.info(`Server is listening on ${config.managePort} serving files on ${staticRoot}`)
2020-09-01 17:31:38 +00:00
})
}