From 73779a32ad1b7823f4b1863ca0c5518b373253e1 Mon Sep 17 00:00:00 2001 From: Your Name Date: Mon, 20 Jan 2025 09:55:48 -0500 Subject: [PATCH] refactor: call ws stuff outside of vm script --- index.js | 35 +++++++++++++++++++++++++++++------ 1 file changed, 29 insertions(+), 6 deletions(-) diff --git a/index.js b/index.js index ed5e2be..fa1bb0a 100644 --- a/index.js +++ b/index.js @@ -19,16 +19,19 @@ const model = require("./db"); const PORT = 3000; const db = model.db; +const wsRouter = express.Router() let viewpath = path.join(__dirname, "views"); let eta = new Eta({ views: viewpath, cache: false, autoEscape: true }); let routes = { GET: [], POST: [], PUT: [], DELETE: [] }; +const wsRoutes = {} app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(express.static("public")); app.use(fileUpload()); +app.use("/", wsRouter); app.use( session({ @@ -109,18 +112,35 @@ function routeWithPrefix(route) { return prefix ? path.join(prefix, route.path) : route.path; } + function bootstrapWebsocketHandler(route) { // todo only expose app when running the handler, should not be available to the handler itself - // need to move to runscript or whatever + // need to move to runscript or whatever...or remove app because we can just call it using the handler? try { const context = bootstrapContext(db, route.structure_id, route.id, { app }); - let result = vm.runInContext( - route.handler + `\n\napp.ws("${routeWithPrefix(route)}", handler)`, - context, - ); + let handler = vm.runInContext(`${route.handler}\n\nhandler;`, context); + + if (!wsRoutes[routeWithPrefix(route)]) { + // initialize ws router. future updates will only require updating + // the wsRoutes dict, not create a whole new route + wsRouter.ws(routeWithPrefix(route), (req, res) => { + return wsRoutes[routeWithPrefix(route)](req, res) + }); + } + + wsRoutes[routeWithPrefix(route)] = (req, res) => { + try { + return handler(req, res) + } catch (e) { + const error = e.stack ? `${e}\n\n${e.stack}` : `${e}`; + model.createLog(db, route.structure_id, route.id, error, true); + throw e; + } + } model.updateRoute(db, { ...route, error: null }); - return result; } catch (e) { + const error = e.stack ? `${e}\n\n${e.stack}` : `${e}`; + model.createLog(db, route.structure_id, route.id, error, true); model.updateRoute(db, { ...route, error: e.stack }); } } @@ -404,6 +424,9 @@ app.post("/workshop/:structure_id/route", (req, res) => { app.put("/workshop/:structure_id/route/:route_id", (req, res) => { const route = model.getRoute(db, req.params.route_id); model.updateRoute(db, { ...route, ...req.body }); + if (route.verb == "WS") { + bootstrapWebsocketHandler({ ...route, ...req.body }) + } return res.send("good"); });