nfp_sites/base/serve.mjs

84 lines
2.4 KiB
JavaScript

import path from 'path'
import dot from 'dot'
import { FileResponse, HttpError } from 'flaska'
import fs from 'fs/promises'
import fsSync from 'fs'
export default class ServeHandler {
constructor(opts = {}) {
Object.assign(this, {
pageRoutes: opts.pageRoutes,
fs: opts.fs || fs,
fsSync: opts.fsSync || fsSync,
root: opts.root,
template: null,
frontend: opts.frontend || 'http://localhost:4000',
version: opts.version || 'version',
})
let indexFile = fsSync.readFileSync(path.join(this.root, 'index.html'))
this.template = dot.template(indexFile.toString(), { argName: ['headerDescription', 'headerImage', 'headerTitle', 'headerUrl', 'payloadData', 'payloadLinks', 'payloadTree', 'version', 'nonce'] })
// console.log(indexFile.toString())
}
register(server) {
server.flaska.get('/::file', this.serve.bind(this))
}
/** 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 (!ctx.params.file || ctx.params.file === 'index.html') {
return this.serveIndex(ctx)
}
if (!file.startsWith(this.root)) {
ctx.status = 404
ctx.body = 'HTTP 404 Error'
return
}
return this.fs.stat(file)
.then(function(stat) {
ctx.body = new FileResponse(file, stat)
})
.catch((err) => {
if (err.code === 'ENOENT') {
return this.serveIndex(ctx)
}
return Promise.reject(err)
})
}
async serveIndex(ctx) {
let payload = {
headerDescription: 'Small fansubbing and scanlation group translating and encoding our favourite shows from Japan.',
headerImage: this.frontend + '/assets/img/heart.png',
headerTitle: 'NFP Moe - Anime/Manga translation group',
headerUrl: this.frontend + ctx.url,
payloadData: null,
payloadLinks: null,
payloadTree: null,
version: this.version,
nonce: ctx.state.nonce,
}
try {
payload.payloadTree = JSON.stringify(await this.pageRoutes.getPageTree(ctx, true))
} catch (e) {
ctx.log.error(e)
}
ctx.body = this.template(payload)
ctx.type = 'text/html; charset=utf-8'
}
serveErrorPage(ctx) {
}
}