import { RouteService, APIRoute, PageRoute, Method } from "../lib/route" import { ExpressService } from "../service/expressService" import * as fs from "fs" import * as pathModule from "path" import * as Leaf from "leaf-ts" export class DefaultPageService extends RouteService { readonly name = "page.default" readonly prefix = "" dependencies = [/api\..+/ig, /page\..+/ig, "ExpressService"] services: { ExpressService: ExpressService } initialize() { this.addRoutes(module.exports) this.installTo(this.services.ExpressService.server) } constructor(option: { page?: { default?: string } } = {}) { super() let config = Leaf.Util.buildOption({ default: null }, option.page || {}) this.defaultPagePath = config.default } public defaultPagePath: string public defaultPageCode = 200 public defaultHTML: string = "" public clearDefaultHTMLCache() { this.defaultHTML = "" } protected generateDefaultHTMLContent(callback: (err, html?: string) => void) { let html: string if (!this.defaultPagePath) { html = "No default content." } else { let path = pathModule.join(this.defaultPagePath) try { html = fs.readFileSync(path, "utf8") this.defaultHTML = html } catch (e) { callback(e) return } } callback(null, html) } public getDefaultPage(callback: (err, html?: string) => void) { if (this.defaultHTML) { callback(null, this.defaultHTML) return } this.generateDefaultHTMLContent((err, html) => { if (err) { callback(err) return } this.defaultHTML = html callback(null, html) }) } public setDefaultHTMLContent(html: string) { this.defaultHTML = html } } export class DefaultPage extends PageRoute { readonly path = "*" service: DefaultPageService handle() { this.service.getDefaultPage((err, html) => { if (err) { this.res.status(503) this.html("ERROR" + err.toString()) return } this.res.status(this.service.defaultPageCode) this.html(html) }) } }