improve hyper-express initialization & support

This commit is contained in:
SrGooglo 2024-09-25 18:40:39 +00:00
parent b1564643ae
commit 16bdc2f211

View File

@ -6,21 +6,24 @@ export default class Engine {
this.params = params this.params = params
} }
app = new he.Server({ app = null
max_body_length: 50 * 1024 * 1024, //50MB in bytes router = null
})
router = new he.Router()
ws = null ws = null
initialize = async (params) => { initialize = async (params) => {
this.app = new he.Server({
max_body_length: 50 * 1024 * 1024, //50MB in bytes,
key_file_name: params.ssl?.key ?? null,
cert_file_name: params.ssl?.cert ?? null,
})
this.router = new he.Router()
// create a router map // create a router map
if (typeof this.router.map !== "object") { if (typeof this.router.map !== "object") {
this.router.map = {} this.router.map = {}
} }
// register 404
await this.router.any("*", (req, res) => { await this.router.any("*", (req, res) => {
return res.status(404).json({ return res.status(404).json({
code: 404, code: 404,
@ -28,24 +31,19 @@ export default class Engine {
}) })
}) })
this.app.use((req, res, next) => {
if (req.method === "OPTIONS") {
return res.status(204).end()
}
next()
})
// register body parser
await this.app.use(async (req, res, next) => { await this.app.use(async (req, res, next) => {
if (req.method === "OPTIONS") { if (req.method === "OPTIONS") {
res.setHeader("Access-Control-Allow-Methods", "*") // handle cors
res.setHeader("Access-Control-Allow-Origin", "*") if (params.ignoreCors) {
res.setHeader("Access-Control-Allow-Headers", "*") res.setHeader("Access-Control-Allow-Methods", "*")
res.setHeader("Access-Control-Allow-Origin", "*")
res.setHeader("Access-Control-Allow-Headers", "*")
}
return res.status(204).end() return res.status(204).end()
} }
// register body parser
if (req.headers["content-type"]) { if (req.headers["content-type"]) {
if (!req.headers["content-type"].startsWith("multipart/form-data")) { if (!req.headers["content-type"].startsWith("multipart/form-data")) {
req.body = await req.urlencoded() req.body = await req.urlencoded()
@ -121,17 +119,18 @@ export default class Engine {
await this.app.listen(this.params.listen_port) await this.app.listen(this.params.listen_port)
} }
close = async () => { // close should be synchronous
if (this.ws.events) { close = () => {
if (this.ws) {
this.ws.clear() this.ws.clear()
}
if (typeof this.ws?.close === "function") { if (typeof this.ws?.close === "function") {
await this.ws.close() this.ws.close()
}
} }
if (typeof this.app?.close === "function") { if (typeof this.app?.close === "function") {
await this.app.close() this.app.close()
} }
} }
} }