2019-10-12 21:08:08 -07:00
|
|
|
// Throttle network requests to be a good citizen and not issue an HTTP request on every keystroke
|
2021-07-04 20:19:04 -07:00
|
|
|
import { PromiseThrottler } from './PromiseThrottler.js'
|
2019-10-12 21:08:08 -07:00
|
|
|
|
|
|
|
const promiseThrottler = new PromiseThrottler(200) // Mastodon FE also uses 200ms
|
|
|
|
|
|
|
|
export class RequestThrottler {
|
2019-10-13 08:08:06 -07:00
|
|
|
constructor (fetcher) {
|
2019-10-12 21:08:08 -07:00
|
|
|
this._canceled = false
|
|
|
|
this._controller = typeof AbortController === 'function' && new AbortController()
|
|
|
|
this._fetcher = fetcher
|
|
|
|
}
|
|
|
|
|
|
|
|
async request () {
|
|
|
|
if (this._canceled) {
|
2019-10-13 08:08:06 -07:00
|
|
|
throw new Error('canceled')
|
2019-10-12 21:08:08 -07:00
|
|
|
}
|
|
|
|
await promiseThrottler.next()
|
|
|
|
if (this._canceled) {
|
2019-10-13 08:08:06 -07:00
|
|
|
throw new Error('canceled')
|
2019-10-12 21:08:08 -07:00
|
|
|
}
|
|
|
|
const signal = this._controller && this._controller.signal
|
2019-10-13 08:08:06 -07:00
|
|
|
return this._fetcher(signal)
|
2019-10-12 21:08:08 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
cancel () {
|
|
|
|
this._canceled = true
|
|
|
|
if (this._controller) {
|
|
|
|
this._controller.abort()
|
|
|
|
this._controller = null
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|