configure devServer & add WebSocket connection at api call

This commit is contained in:
Axolotle 2020-10-09 22:05:23 +02:00
parent b71aeda651
commit e2a13f4c35
3 changed files with 42 additions and 7 deletions

View file

@ -103,6 +103,25 @@ export default {
}
},
/**
* Opens a WebSocket connection to the server in case it sends messages.
* Currently, the connection is closed by the server right after an API call so
* we have to open it for every calls.
* Messages are dispatch to the store so it can handle them.
*
* @return {Promise<Event>} Promise that resolve on websocket 'open' or 'error' event.
*/
openWebSocket () {
return new Promise(resolve => {
const ws = new WebSocket(`wss://${store.getters.host}/yunohost/api/messages`)
ws.onmessage = ({ data }) => store.dispatch('DISPATCH_MESSAGE', JSON.parse(data))
// ws.onclose = (e) => {}
ws.onopen = resolve
// Resolve also on error so the actual fetch may be called.
ws.onerror = resolve
})
},
/**
* Generic method to fetch the api without automatic response handling.
*
@ -111,12 +130,16 @@ export default {
* @param {string} [data={}] - data to send as body for 'POST', 'PUT' and 'DELETE' methods.
* @return {Promise<Response>} Promise that resolve a fetch `Response`.
*/
fetch (method, uri, data = {}) {
async fetch (method, uri, data = {}) {
// Open a websocket connection that will dispatch messages received.
// FIXME add ability to do not open it
await this.openWebSocket()
if (method === 'GET') {
const localeQs = `${uri.includes('?') ? '&' : '?'}locale=${store.getters.locale}`
return fetch('/api/' + uri + localeQs, this.options)
return fetch('/yunohost/api/' + uri + localeQs, this.options)
}
return fetch('/api/' + uri, {
return fetch('/yunohost/api/' + uri, {
...this.options,
method,
body: objectToParams(data, { addLocale: true })

View file

@ -5,7 +5,8 @@ export default {
state: {
connected: localStorage.getItem('connected') === 'true',
yunohost: null, // yunohost app infos: Object {version, repo}
waiting: false
waiting: false,
host: window.location.host
},
mutations: {
@ -77,12 +78,17 @@ export default {
}
throw err
})
},
'DISPATCH_MESSAGE' (store, message) {
console.log(message)
}
},
getters: {
connected: state => (state.connected),
yunohost: state => (state.yunohost),
waiting: state => state.waiting
waiting: state => state.waiting,
host: state => state.host
}
}

View file

@ -52,10 +52,16 @@ module.exports = {
}
},
devServer: {
https: true,
proxy: {
'^/api': {
target: `https://${process.env.VUE_APP_IP}/yunohost`
'^/yunohost': {
target: `https://${process.env.VUE_APP_IP}`,
ws: true,
logLevel: 'debug'
}
},
watchOptions: {
ignored: /node_modules/
}
}
}