remote.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import express from 'express';
  2. import log from './log.js';
  3. import RemoteCode from './remoteCode.js';
  4. import { throwError, errorGuard, errorMiddleware } from './error.js';
  5. // Remote setup Middleware
  6. export const remote = ({
  7. setupPath = 'setup.js',
  8. context = {},
  9. disableCache,
  10. preProcess,
  11. } = {}) => {
  12. const router = express.Router();
  13. const setupLoaded = {};
  14. // Remote code caller
  15. const remoteCode = new RemoteCode({
  16. disableCache,
  17. preProcess,
  18. });
  19. router.use(
  20. errorGuard(async (req, res, next) => {
  21. const {
  22. query: { clearCache },
  23. ricochetOrigin: remote,
  24. } = req;
  25. if (clearCache) {
  26. remoteCode.clearCache(remote);
  27. log.info(`Clear cache for ${remote}`);
  28. }
  29. if (!setupLoaded[remote] || disableCache || clearCache) {
  30. try {
  31. let contextAddition = context;
  32. if (typeof context === 'function') {
  33. contextAddition = context(req);
  34. }
  35. await remoteCode.exec(req, remote, setupPath, {
  36. ...contextAddition,
  37. });
  38. setupLoaded[remote] = true;
  39. log.info(`Setup successfully loaded from ${remote}`);
  40. } catch (e) {
  41. log.warn({ error: e }, `Fails to load setup from ${remote}`);
  42. throwError(e, 500);
  43. }
  44. }
  45. next();
  46. })
  47. );
  48. router.get(`/ping`, async (req, res) => {
  49. res.send('ok');
  50. });
  51. router.use(errorMiddleware);
  52. return router;
  53. };
  54. export default remote;