nfp_sites/api/serve.mjs

38 lines
995 B
JavaScript
Raw Normal View History

import path from 'path'
import { FileResponse, HttpError } 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) {
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(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)
})
}
}