Skip to content

Instantly share code, notes, and snippets.

@stefandobre
Last active June 11, 2023 12:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stefandobre/5b7bd0843f09de533af31a6db908620d to your computer and use it in GitHub Desktop.
Save stefandobre/5b7bd0843f09de533af31a6db908620d to your computer and use it in GitHub Desktop.
// fetch the library from the table
const loadFromDatabase = (moduleName) => {
const result = apex.conn.execute(`
select source
  from javascript_modules
  where module_name = :name
`, {
name: moduleName
}, {
fetchInfo: {
SOURCE: {
type: apex.db.STRING
}
}
});
return result.rows[0].SOURCE;
};
// module decoration. similar to how node.js operates
const decorateModule = (module) => `
(function () {
  let exports = {},
  module = {exports: exports};
  ${module};
  return module.exports;
})();
`;
// cache modules in case they are required multiple times
const moduleCache = {};
// expose the requireModule function globally
globalThis.requireModule = (moduleName) => {
if (!moduleCache[moduleName]) {
const moduleString = decorateModule(loadFromDatabase(moduleName));
moduleCache[moduleName] = Polyglot.eval('js', moduleString);
}
return moduleCache[moduleName];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment