sse.ts 807 B

12345678910111213141516171819202122232425262728
  1. import {Plugin} from "@nuxt/types";
  2. import SseSource from "~/services/sse/sseSource";
  3. /**
  4. * Setup SSE EventSource, allowing the app to listen for Mercure updates
  5. * /!\ This has to be executed client side
  6. *
  7. * @param ctx
  8. */
  9. const ssePlugin: Plugin = ({ $config, store }) => {
  10. if (!$config.baseUrl_mercure) {
  11. console.error('Mercure : the hub url is not defined')
  12. return;
  13. }
  14. const sseSource = new SseSource(
  15. $config.baseUrl_mercure,
  16. "access/" + store.state.profile.access.id,
  17. () => { store.commit('sse/setConnected', true) },
  18. (eventData) => { store.commit('sse/addEvent', eventData) },
  19. () => { store.commit('sse/setConnected', false) },
  20. )
  21. sseSource.subscribe()
  22. window.addEventListener('beforeunload', () => { sseSource.unsubscribe() })
  23. }
  24. export default ssePlugin