execute.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import express from 'express';
  2. import { errorGuard, errorMiddleware } from './error.js';
  3. /* Roadmap
  4. - Allow to register new site
  5. - Return public key if no key pair is given
  6. - Allow to sign code
  7. */
  8. // Execute Middleware
  9. export const exec = ({
  10. prefix = 'execute',
  11. context = {},
  12. functions = {},
  13. } = {}) => {
  14. const router = express.Router();
  15. // Route all query to correct script
  16. router.all(
  17. `/${prefix}/:functionName/:id?`,
  18. errorGuard(async (req, res) => {
  19. const {
  20. body,
  21. params: { functionName, id },
  22. query,
  23. method,
  24. authenticatedUser = null,
  25. } = req;
  26. let allFunctions = functions;
  27. if (typeof functions === 'function') {
  28. allFunctions = functions(req);
  29. }
  30. if (!allFunctions[functionName]) {
  31. res.status(404).send('Not found');
  32. return;
  33. }
  34. let contextAddition = context;
  35. if (typeof context === 'function') {
  36. contextAddition = context(req);
  37. }
  38. const result = await allFunctions[functionName]({
  39. query,
  40. body,
  41. method,
  42. id,
  43. userId: authenticatedUser,
  44. ...contextAddition,
  45. });
  46. res.json(result);
  47. })
  48. );
  49. router.use(errorMiddleware);
  50. return router;
  51. };
  52. export default exec;