39 lines
998 B
JavaScript
39 lines
998 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._lastState = { internet: false }
|
|
this._action(this._lastState)
|
|
this._update()
|
|
}
|
|
|
|
async _update () {
|
|
let nextState
|
|
try {
|
|
const hasInternet = await isOnline(this.opts)
|
|
nextState = { internet: hasInternet }
|
|
} catch (err) {
|
|
nextState = { internet: hasInternet }
|
|
} finally {
|
|
this._timeout = setTimeout(() => this._update(), this.retryInterval)
|
|
}
|
|
nextState.changed = nextState.internet !== this._lastState.internet
|
|
this._action(nextState)
|
|
this._lastState = nextState
|
|
}
|
|
|
|
_destroy () {
|
|
if (this._timeout) clearTimeout(this._timeout)
|
|
}
|
|
|
|
_action (data) {
|
|
if (this.destroyed) return
|
|
this.push(action(CONNECTIVITY, data))
|
|
}
|
|
}
|