34 lines
808 B
JavaScript
34 lines
808 B
JavaScript
|
import path from 'path'
|
||
|
import { FileResponse } from 'flaska'
|
||
|
import fs from 'fs/promises'
|
||
|
|
||
|
export default class ServeHandler {
|
||
|
constructor(opts = {}) {
|
||
|
Object.assign(this, {
|
||
|
fs: opts.fs || fs,
|
||
|
root: opts.root,
|
||
|
})
|
||
|
}
|
||
|
|
||
|
/** GET: /::file */
|
||
|
serve(ctx) {
|
||
|
let file = path.resolve(path.join(this.root, ctx.params.file ? ctx.params.file : 'index.html'))
|
||
|
|
||
|
if (!file.startsWith(this.root)) {
|
||
|
ctx.status = 404
|
||
|
ctx.body = 'HTTP 404 Error'
|
||
|
return
|
||
|
}
|
||
|
|
||
|
return this.fs.stat(file).catch((err) => {
|
||
|
if (err.code === 'ENOENT') {
|
||
|
file = path.resolve(path.join(this.root, 'index.html'))
|
||
|
return this.fs.stat(file)
|
||
|
}
|
||
|
return Promise.reject(err)
|
||
|
})
|
||
|
.then(function(stat) {
|
||
|
ctx.body = new FileResponse(file, stat)
|
||
|
})
|
||
|
}
|
||
|
}
|