import path from 'path' import fs from 'fs/promises' import { Flaska, FileResponse, HttpError } from 'flaska' export function run(http, port, core) { let localUtil = new core.sc.Util(import.meta.url) const staticRoot = localUtil.getPathFromRoot('../public') 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}`) }) flaska.get('/::file', function(ctx) { if (ctx.params.file.startsWith('api/')) { throw new HttpError(404, 'Not Found: ' + ctx.params.file, { status: 404, message: 'Not Found: ' + ctx.params.file }) } let file = path.resolve(path.join(staticRoot, ctx.params.file ? ctx.params.file : 'index.html')) if (!file.startsWith(staticRoot)) { ctx.status = 404 ctx.body = 'HTTP 404 Error' return } return fs.stat(file).catch(function(err) { if (err.code === 'ENOENT') { file = path.resolve(path.join(staticRoot, 'index.html')) return fs.stat(file) } return Promise.reject(err) }) .then(function(stat) { ctx.body = new FileResponse(file, stat) }) }) return flaska.listenAsync(port).then(function() { core.log.info('Server is listening on port ' + port) }) }