import path from 'path' import { FileResponse } from 'flaska' import fs from 'fs/promises' import fsSync from 'fs' export default class ServeHandler { constructor(opts = {}) { Object.assign(this, opts) Object.assign(this, { fs: this.fs || fs, fsSync: this.fsSync || fsSync, frontend: this.frontend || 'http://localhost:4000', version: this.version || 'version', }) this.index = fsSync.readFileSync(path.join(this.root, 'index.html')) } register(server) { server.flaska.get('/::file', this.serve.bind(this)) } /** GET: /::file */ serve(ctx) { if (ctx.params.file.startsWith('api/')) { return this.serveIndex(ctx) } let file = path.resolve(path.join(this.root, ctx.params.file ? ctx.params.file : 'index.html')) if (!ctx.params.file || ctx.params.file === 'index.html') { return this.serveIndex(ctx) } if (!file.startsWith(this.root)) { return this.serveIndex(ctx) } return this.fs.stat(file) .then(function(stat) { ctx.headers['Cache-Control'] = 'no-store' ctx.body = new FileResponse(file, stat) }) .catch((err) => { if (err.code === 'ENOENT') { return this.serveIndex(ctx) } return Promise.reject(err) }) } async serveIndex(ctx) { ctx.body = this.index ctx.type = 'text/html; charset=utf-8' } serveErrorPage(ctx) { } }