-
-
Save szmarczak/0f2b70b2a1ed52a56a6d391ac02d094d to your computer and use it in GitHub Desktop.
This file contains 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
// 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