Update WebSocket config to accept an object

The `websockets` parameter can now be an object, allowing
`enabled` and `path` to be specified for finer control.
Server startup log now displays the WebSocket path.
This commit is contained in:
SrGooglo 2025-05-11 20:47:17 +00:00
parent bc9b82dab1
commit 8046293b3c
2 changed files with 25 additions and 14 deletions

View File

@ -26,11 +26,12 @@ export default class Engine {
this.app.use(this.mainMiddleware) this.app.use(this.mainMiddleware)
this.app.use(this.router) this.app.use(this.router)
if (this.server.params.websockets === true) { if (typeof this.server.params.websockets === "object") {
const { path, enabled } = this.server.params.websockets
if (enabled === true) {
this.ws = new RtEngine({ this.ws = new RtEngine({
path: path: path ?? `/${this.server.params.refName}`,
this.server.params.wsPath ??
`/${this.server.params.refName}`,
onUpgrade: this.server.handleWsUpgrade, onUpgrade: this.server.handleWsUpgrade,
onConnection: this.server.handleWsConnection, onConnection: this.server.handleWsConnection,
onDisconnect: this.server.handleWsDisconnect, onDisconnect: this.server.handleWsDisconnect,
@ -41,6 +42,7 @@ export default class Engine {
this.ws.attach(this) this.ws.attach(this)
} }
} }
}
mainMiddleware = async (req, res, next) => { mainMiddleware = async (req, res, next) => {
if (req.method === "OPTIONS") { if (req.method === "OPTIONS") {

View File

@ -72,6 +72,10 @@ class Server {
this.params.wsRoutesPath = this.constructor.wsRoutesPath this.params.wsRoutesPath = this.constructor.wsRoutesPath
} }
if (typeof this.constructor.websockets === "object") {
this.params.websockets = this.constructor.websockets
}
if (typeof this.constructor.useMiddlewares !== "undefined") { if (typeof this.constructor.useMiddlewares !== "undefined") {
if (!Array.isArray(this.constructor.useMiddlewares)) { if (!Array.isArray(this.constructor.useMiddlewares)) {
this.constructor.useMiddlewares = [ this.constructor.useMiddlewares = [
@ -219,9 +223,14 @@ class Server {
const elapsedHrTime = process.hrtime(startHrTime) const elapsedHrTime = process.hrtime(startHrTime)
const elapsedTimeInMs = elapsedHrTime[0] * 1e3 + elapsedHrTime[1] / 1e6 const elapsedTimeInMs = elapsedHrTime[0] * 1e3 + elapsedHrTime[1] / 1e6
console.info( const lines = [
`🛰 Server ready!\n\t - ${this.hasSSL ? "https" : "http"}://${this.params.listenIp}:${this.params.listenPort} \n\t - Websocket: ${this.engine.ws ? "Enabled" : "Disabled"} \n\t - Routes: ${this.engine.map.size} \n\t - Tooks: ${elapsedTimeInMs.toFixed(2)}ms \n\t `, `- Url: ${this.hasSSL ? "https" : "http"}://${this.params.listenIp}:${this.params.listenPort}`,
) `- Websocket: ${this.engine.ws ? this.engine.ws?.config?.path : "Disabled"}`,
`- Routes: ${this.engine.map.size}`,
`- Tooks: ${elapsedTimeInMs.toFixed(2)}ms`,
]
console.info(`🛰 Server ready!\n \t${lines.join("\n\t")} \n`)
} }
register = { register = {