knowyt/client/src/plugins/engine.js

65 lines
1.6 KiB
JavaScript
Raw Normal View History

2021-08-05 02:22:28 +02:00
import buildUrl from 'build-url'
2021-07-30 21:03:43 +02:00
export default (context, inject) => {
2021-08-05 02:22:28 +02:00
const { store, $axios, $config } = context
2021-07-30 21:03:43 +02:00
const engine = {
lastFetched: [0, 0, 0, 0, 0],
2021-08-05 02:22:28 +02:00
async start() {
if (!store.state.engine.user) {
if (!await this.fetchUserInfo()) {
window.location.href = "/"
}
2021-08-05 02:22:28 +02:00
}
2021-07-30 21:03:43 +02:00
this.fetchUpdate()
},
async fetchUpdate() {
let delay = 0
try {
2021-08-05 02:22:28 +02:00
const url = buildUrl($config.serverBaseUrl, {
path: '/api/sync',
queryParams: {
v: store.state.engine.version + 1,
g: store.state.engine.user?.game,
},
})
const response = await $axios.get(url)
2021-07-30 21:03:43 +02:00
const json = response.data
store.commit('engine/setJson', json)
} catch (e) {
const { status, statusText } = e.response
2021-08-05 01:04:53 +02:00
if (status != 200) {
2021-07-30 21:03:43 +02:00
console.warn(`HTTP ${status} ${statusText}`)
delay = 5000
2021-07-30 21:49:39 +02:00
store.commit('engine/setVersion', -1)
2021-07-30 21:03:43 +02:00
}
}
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)
},
async fetchUserInfo() {
try {
const user = await $axios.$get('/api/userinfo')
store.commit('engine/setUser', user)
} catch(e) {
store.commit('engine/setUser', undefined)
return false
}
return true
},
2021-07-30 21:03:43 +02:00
}
inject('engine', engine)
}