Created
January 19, 2022 22:06
-
-
Save kevinswiber/eb4312fe71b765416ff7d7854f372800 to your computer and use it in GitHub Desktop.
Import external dependencies into Postman
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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