diff --git a/app/src/helpers/api.js b/app/src/helpers/api.js index 378e6b51..4f224b9d 100644 --- a/app/src/helpers/api.js +++ b/app/src/helpers/api.js @@ -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} 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} 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 }) diff --git a/app/src/store/info.js b/app/src/store/info.js index c4e90d00..c94d0601 100644 --- a/app/src/store/info.js +++ b/app/src/store/info.js @@ -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 } } diff --git a/app/vue.config.js b/app/vue.config.js index 7aaf8f0b..b8f6973d 100644 --- a/app/vue.config.js +++ b/app/vue.config.js @@ -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/ } } }