2024-02-13 23:54:45 +00:00
|
|
|
import path from 'path'
|
2024-02-20 04:57:49 +00:00
|
|
|
import dot from 'dot'
|
2024-02-13 23:54:45 +00:00
|
|
|
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'))
|
2024-02-20 04:57:49 +00:00
|
|
|
this.loadTemplate(this.index)
|
|
|
|
}
|
|
|
|
|
|
|
|
loadTemplate(indexFile) {
|
|
|
|
this.template = dot.template(indexFile.toString(), { argName: [
|
|
|
|
'version'
|
|
|
|
], strip: false })
|
2024-02-13 23:54:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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) {
|
2024-02-20 04:57:49 +00:00
|
|
|
ctx.body = this.template({ version: this.version })
|
2024-02-13 23:54:45 +00:00
|
|
|
ctx.type = 'text/html; charset=utf-8'
|
|
|
|
}
|
|
|
|
|
|
|
|
serveErrorPage(ctx) {
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|