40 lines
990 B
JavaScript
40 lines
990 B
JavaScript
|
|
||
|
export default (context, inject) => {
|
||
|
const { store, $axios } = context
|
||
|
|
||
|
const engine = {
|
||
|
lastFetched: [0, 0, 0, 0, 0],
|
||
|
start() {
|
||
|
this.fetchUpdate()
|
||
|
},
|
||
|
async fetchUpdate() {
|
||
|
let delay = 0
|
||
|
try {
|
||
|
const response = await $axios.get('http://localhost:3000/api/sync?v=' + (store.state.engine.version + 1))
|
||
|
const json = response.data
|
||
|
store.commit('engine/setJson', json)
|
||
|
} catch (e) {
|
||
|
const { status, statusText } = e.response
|
||
|
if (status >= 500) {
|
||
|
console.warn(`HTTP ${status} ${statusText}`)
|
||
|
delay = 5000
|
||
|
}
|
||
|
}
|
||
|
|
||
|
const now = new Date().getTime()
|
||
|
const last = this.lastFetched.splice(0, 1)
|
||
|
this.lastFetched.push(now)
|
||
|
|
||
|
if (now - last < 1000) {
|
||
|
console.warn('engine: respawning too fast, throttling down')
|
||
|
delay = 5000
|
||
|
}
|
||
|
window.setTimeout(() => {
|
||
|
this.fetchUpdate()
|
||
|
}, delay)
|
||
|
},
|
||
|
|
||
|
}
|
||
|
inject('engine', engine)
|
||
|
}
|