import { Service } from "../lib/service" import * as express from "express" import * as bodyParser from "body-parser" import { MongodbService } from "./mongodbService" import * as http from "http" export class ExpressService extends Service { name = "ExpressService" as "ExpressService" dependencies = [] services: {} server: express.Application constructor(settings: Type.Root.ExpressService.Settings) { super({ http: { port: 8080, host: "0.0.0.0", offline: false, limit: { bodyInKb: 1024 * 8, jsonInKb: null, }, staticResources: [] }, }, settings) let staticResources = this.settings.http.staticResources || [] for (let res of staticResources) { this.static(res.path, res.route) } } httpServer: http.Server initialize(done) { this.server = express() for (let info of this.staticPathes) { this.useStatic(info) } let { jsonInKb, bodyInKb } = this.settings.http.limit this.server.use(bodyParser.json({ limit: (jsonInKb || bodyInKb || 1024) + "kb" })); // for parsing application/json this.server.use(bodyParser.urlencoded({ extended: true, limit: (bodyInKb || 1024) + "kb" })); // for parsing application/x-www-form-urlencoded if (!this.settings.http.offline) { this.initHttp(() => { done() }) } else { done() } } public initHttp(callback: Function) { let { host, port } = this.settings.http this.httpServer = this.server.listen(parseInt(port.toString()), host, () => { console.log("Express listen at", `${host}:${port}`) callback() }) } asBuiltIn() { let { host, port } = this.settings.http console.log(`ExpressService default http://${host}:${port}/`) } private staticPathes: { route?: string path: string }[] = [] static(path: string, route?: string) { this.staticPathes.push({ path, route }) if (this.server) { this.useStatic(this.staticPathes[this.staticPathes.length - 1]) } } private useStatic(info: { route?: string, path: string }) { if (!info.path) { console.error(info) console.error("Static resource requires a path") return } if (info.route) { this.server.use(info.route, express.static(info.path)) } else { this.server.use(express.static(info.path)) } } }