Skip to content

Instantly share code, notes, and snippets.

@szmarczak
Last active July 17, 2021 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save szmarczak/0f2b70b2a1ed52a56a6d391ac02d094d to your computer and use it in GitHub Desktop.
Save szmarczak/0f2b70b2a1ed52a56a6d391ac02d094d to your computer and use it in GitHub Desktop.
// wrapped-got.js
'use strict';
let got;
let instance;
// Your custom defaults here
const defaults = {
mutableDefaults: false
};
const lazy = async (args, onPromise) => {
if (got === undefined) {
got = await import('got');
instance = got.default.extend(defaults);
Object.assign(module.exports, got);
Object.assign(module.exports, instance);
}
const promise = instance(...args);
onPromise(promise);
return promise;
};
module.exports = (...args) => {
if (instance !== undefined) {
return instance(...args);
}
let resolve;
let actualPromise;
const promiseToPromise = new Promise(_resolve => {
resolve = _resolve;
});
const promise = lazy(args, _actualPromise => {
actualPromise = _actualPromise;
resolve();
});
const generate = name => {
return async (...args) => {
const promise = (async () => {
await promiseToPromise;
return actualPromise[name](...args);
})();
apply(promise);
return promise;
};
};
const apply = promise => {
promise.json = generate('json');
promise.text = generate('text');
promise.buffer = generate('buffer');
promise.cancel = generate('cancel');
};
apply(promise);
return promise;
};
// demo.js
const cjs = module.exports; // require('./wrapped-got.js');
(async () => {
console.log(cjs.defaults === undefined); // true
{
const response = await cjs('https://httpbin.org/anything').json();
console.log(response);
}
console.log(cjs.defaults === undefined); // false
// Now it is safe to use streams etc.
cjs.stream('https://httpbin.org/anything').pipe(process.stdout);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment