refactor: call ws stuff outside of vm script

This commit is contained in:
Your Name 2025-01-20 09:55:48 -05:00
parent 445fa4803a
commit 73779a32ad

View file

@ -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");
});