Skip to content

Instantly share code, notes, and snippets.

@kevinswiber
Created January 19, 2022 22:06
Show Gist options
  • Save kevinswiber/eb4312fe71b765416ff7d7854f372800 to your computer and use it in GitHub Desktop.
Save kevinswiber/eb4312fe71b765416ff7d7854f372800 to your computer and use it in GitHub Desktop.
Import external dependencies into Postman
const CACHE_KEY = '__importCache'
const importCacheLayer = pm.environment.has(CACHE_KEY)
? pm.environment
: pm.collectionVariables.has(CACHE_KEY)
? pm.collectionVariables
: pm.globals.has(CACHE_KEY)
? pm.globals
: pm.variables;
const __import = (url, options = { timeout: 20_000}) => {
const moduleCacheKey = `${CACHE_KEY}:${url}`;
if (importCacheLayer.has(moduleCacheKey)) {
return Promise.resolve(new Function(importCacheLayer.get(moduleCacheKey))());
}
return new Promise((resolve, reject) => {
const fetchTimeout = setTimeout(() => {
reject(new Error(`timeout waiting for import: ${url}`));
}, options.timeout);
pm.sendRequest(url, (err, res) => {
if (err) {
reject(err);
clearTimeout(fetchTimeout);
return;
}
const contents = res.text();
if (JSON.parse(importCacheLayer.get(CACHE_KEY) || 0)) {
importCacheLayer.set(moduleCacheKey, contents);
}
resolve(new Function(contents)());
clearTimeout(fetchTimeout);
});
});
};
(async function main() {
await __import('https://cdn.jsdelivr.net/npm/js-yaml');
console.log(jsyaml.load(`---
hi: there`));
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment