client engine

This commit is contained in:
Settel 2021-07-30 21:03:43 +02:00
parent 1d26fdce8c
commit 56cd5b4698
5 changed files with 45 additions and 5 deletions

View File

@ -14,6 +14,7 @@ export default {
},
components: true,
modules: ['@nuxtjs/axios'],
plugins: [{ src: '~/plugins/engine.js', mode: 'client' }],
axios: { proxy: true },
proxy: {
'/api/': 'http://localhost:32039',

View File

@ -6,14 +6,12 @@
<script>
export default {
async fetch() {
const response = await this.$axios.get('http://localhost:3000/api/sync')
const json = response.data
this.$store.commit('setJson', json)
mounted() {
this.$engine.start()
},
computed: {
json() {
return JSON.stringify(this.$store.state.json, null, 2)
return JSON.stringify(this.$store.state.engine.json, null, 2)
},
}
}

View File

@ -0,0 +1,39 @@
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)
}

View File

@ -1,9 +1,11 @@
export const state = () => ({
json: {},
version: -1,
})
export const mutations = {
setJson(state, json) {
state.json = json
state.version = parseInt(json.version, 10)
}
}