mirror of
https://git.sr.ht/~cadence/bibliogram
synced 2024-11-16 13:17:30 +00:00
42 lines
1019 B
JavaScript
42 lines
1019 B
JavaScript
|
const constants = require("../constants")
|
||
|
const {request} = require("./request")
|
||
|
|
||
|
class TorSwitcher {
|
||
|
constructor() {
|
||
|
this.torManager = null
|
||
|
}
|
||
|
|
||
|
setManager(torManager) {
|
||
|
this.torManager = torManager
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Request from the URL.
|
||
|
* The test function will be called with the response object.
|
||
|
* If the test function succeeds, its return value will be returned here.
|
||
|
* If the test function fails, its error will be rejected here.
|
||
|
* Only include rate limit logic in the test function!
|
||
|
* @param {string} url
|
||
|
* @param {(res: import("node-fetch").Response) => Promise<T>} test
|
||
|
* @returns {Promise<T>}
|
||
|
* @template T the return value of the test function
|
||
|
*/
|
||
|
request(url, test) {
|
||
|
if (this.torManager) {
|
||
|
return this.torManager.request(url, test)
|
||
|
} else {
|
||
|
return request(url).then(res => test(res))
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
const switcher = new TorSwitcher()
|
||
|
|
||
|
if (constants.use_tor) {
|
||
|
require("./tor").then(torManager => {
|
||
|
if (torManager) switcher.setManager(torManager)
|
||
|
})
|
||
|
}
|
||
|
|
||
|
module.exports = switcher
|