import { Flaska, QueryHandler } from 'flaska' import { WebSocket, WebSocketServer } from 'ws' import ServeHandler from './serve.mjs' export function run(http, port, core) { let localUtil = new core.sc.Util(import.meta.url) // Create our server const flaska = new Flaska({ log: core.log, }, http) flaska.before(function(ctx) { ctx.state.started = new Date().getTime() }) // 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' } ctx.log[level]({ duration: requestTime, status: ctx.status, }, `<-- ${status}${ctx.method} ${ctx.url}`) }) const serve = new ServeHandler({ root: localUtil.getPathFromRoot('../public'), }) flaska.get('/::file', serve.serve.bind(serve)) return flaska.listenAsync(port).then(function() { const wss = new WebSocketServer({ server: flaska.server }) wss.on('connection', function(ws) { console.log('new connection') ws.isAlive = true ws.on('pong', function() { ws.isAlive = true }) ws.on('message', function message(data, isBinary) { if (isBinary) { return console.log('got binary, not supported') } let payload try { payload = JSON.parse(data.toString()) } catch (err) { core.log.error(err) return } console.log('got', payload) wss.clients.forEach(function each(client) { if (client.readyState === WebSocket.OPEN) { client.send(JSON.stringify(payload)); } }) }) }) const interval = setInterval(function() { if (wss.clients.length > 0) { core.log.info('Connected clients: ' + wss.clients.length) } wss.clients.forEach(function(ws) { if (ws.isAlive === false) { return ws.terminate() } ws.isAlive = false ws.ping() }) }, 5000) wss.on('close', function() { clearInterval(interval) }) core.log.info('Server is listening on port ' + port) }) }