fix registerHTTPEndpoint is has incorrect http method alias

This commit is contained in:
srgooglo 2022-05-06 10:27:43 +02:00
parent 70e319665a
commit 604edd49ae

View File

@ -15,7 +15,7 @@ const { serverManifest } = require("../lib")
global.LOCALHOST_ADDRESS = net.ip.getHostAddress() ?? "localhost" global.LOCALHOST_ADDRESS = net.ip.getHostAddress() ?? "localhost"
global.FIXED_HTTP_METHODS = { global.FIXED_HTTP_METHODS = {
"delete": "del", "del": "delete"
} }
global.VALID_HTTP_METHODS = ["get", "post", "put", "patch", "del", "delete", "trace", "head", "any", "options", "ws"] global.VALID_HTTP_METHODS = ["get", "post", "put", "patch", "del", "delete", "trace", "head", "any", "options", "ws"]
global.DEFAULT_HEADERS = { global.DEFAULT_HEADERS = {
@ -34,14 +34,18 @@ const defaultMiddlewares = [
}), }),
] ]
const FixedMethods = {
"delete": "del",
}
if (process.env.NODE_ENV !== "production") { if (process.env.NODE_ENV !== "production") {
defaultMiddlewares.push(require("morgan")("dev")) defaultMiddlewares.push(require("morgan")("dev"))
} }
function outputServerError({
message = "Unexpected error",
description,
ref = "SERVER",
}) {
console.error(`\n\x1b[41m\x1b[37m🆘 [${ref}] ${message}\x1b[0m ${description ? `\n ${description}` : ""} \n`)
}
class Server { class Server {
constructor(params = {}, controllers = [], middlewares = {}) { constructor(params = {}, controllers = [], middlewares = {}) {
this.params = { ...params } this.params = { ...params }
@ -150,6 +154,8 @@ class Server {
try { try {
const ControllerInstance = new controller() const ControllerInstance = new controller()
// get endpoints from controller (ComplexController)
const HTTPEndpoints = ControllerInstance.getEndpoints() const HTTPEndpoints = ControllerInstance.getEndpoints()
const WSEndpoints = ControllerInstance.getWSEndpoints() const WSEndpoints = ControllerInstance.getWSEndpoints()
@ -161,7 +167,11 @@ class Server {
this.registerWSEndpoint(endpoint) this.registerWSEndpoint(endpoint)
}) })
} catch (error) { } catch (error) {
console.error(`🆘 [${controller.refName}] Failed to initialize controller: ${error.message}`) outputServerError({
message: "Controller initialization failed:",
description: error.stack,
ref: controller.refName ?? controller.name,
})
} }
} }
} }
@ -170,8 +180,13 @@ class Server {
// check and fix method // check and fix method
endpoint.method = endpoint.method?.toLowerCase() ?? "get" endpoint.method = endpoint.method?.toLowerCase() ?? "get"
if (FixedMethods[endpoint.method]) { if (global.FIXED_HTTP_METHODS[endpoint.method]) {
endpoint.method = FixedMethods[endpoint.method] endpoint.method = global.FIXED_HTTP_METHODS[endpoint.method]
}
// check if method is supported
if (typeof this.httpInterface[endpoint.method] !== "function") {
throw new Error(`Method [${endpoint.method}] is not supported!`)
} }
// grab the middlewares // grab the middlewares
@ -186,6 +201,12 @@ class Server {
this.endpointsMap[endpoint.method] = {} this.endpointsMap[endpoint.method] = {}
} }
// create model for http interface router
const routeModel = [endpoint.route, ...middlewares, this.createHTTPRequestHandler(endpoint)]
// register endpoint to http interface router
this.httpInterface[endpoint.method](...routeModel)
// extend to map // extend to map
this.endpointsMap[endpoint.method] = { this.endpointsMap[endpoint.method] = {
...this.endpointsMap[endpoint.method], ...this.endpointsMap[endpoint.method],
@ -194,9 +215,6 @@ class Server {
enabled: endpoint.enabled ?? true, enabled: endpoint.enabled ?? true,
}, },
} }
// set handler
this.httpInterface[endpoint.method](endpoint.route, ...middlewares, this.handleHTTPRequest)
} }
registerWSEndpoint = (endpoint, ...execs) => { registerWSEndpoint = (endpoint, ...execs) => {
@ -260,21 +278,23 @@ class Server {
} }
// handlers // handlers
handleHTTPRequest = async (req, res) => { createHTTPRequestHandler = (endpoint) => {
try { return async (req, res) => {
// check if endpoint is disabled try {
if (!this.endpointsMap[endpoint.method][endpoint.route].enabled) { // check if endpoint is disabled
throw new Error("Endpoint is disabled!") if (!this.endpointsMap[endpoint.method][endpoint.route].enabled) {
} throw new Error("Endpoint is disabled!")
}
return await endpoint.fn(req, res) return await endpoint.fn(req, res)
} catch (error) { } catch (error) {
if (typeof this.params.onRouteError === "function") { if (typeof this.params.onRouteError === "function") {
return this.params.onRouteError(req, res, error) return this.params.onRouteError(req, res, error)
} else { } else {
return res.status(500).json({ return res.status(500).json({
"error": error.message "error": error.message
}) })
}
} }
} }
} }