sc-manager/api/server.mjs

84 lines
2.3 KiB
JavaScript
Raw Normal View History

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