34 lines
808 B
JavaScript
34 lines
808 B
JavaScript
import isOnline from 'is-online'
|
|
import { Readable } from 'streamx'
|
|
|
|
import { action, CONNECTIVITY } from '../state.mjs'
|
|
|
|
export class ConnectivityCheck extends Readable {
|
|
constructor (opts = {}) {
|
|
super()
|
|
this.opts = opts
|
|
this.retryInterval = opts.retryInterval || 2000
|
|
this._action({ internet: false })
|
|
this._update()
|
|
}
|
|
|
|
async _update () {
|
|
try {
|
|
const hasInternet = await isOnline(this.opts)
|
|
this._action({ internet: hasInternet })
|
|
} catch (err) {
|
|
this._action({ internet: false })
|
|
} finally {
|
|
this._timeout = setTimeout(() => this._update(), this.retryInterval)
|
|
}
|
|
}
|
|
|
|
_destroy () {
|
|
if (this._timeout) clearTimeout(this._timeout)
|
|
}
|
|
|
|
_action (data) {
|
|
if (this.destroyed) return
|
|
this.push(action(CONNECTIVITY, data))
|
|
}
|
|
}
|