Browse Source

add sse service and plugin

Olivier Massot 3 years ago
parent
commit
7aff84d32d
3 changed files with 18 additions and 2 deletions
  1. 1 0
      config/nuxtConfig/plugins.js
  2. 15 0
      plugins/sse.ts
  3. 2 2
      services/sse/sseSource.ts

+ 1 - 0
config/nuxtConfig/plugins.js

@@ -10,6 +10,7 @@ export default {
     '~/plugins/Data/dataProvider',
     '~/plugins/Data/dataDeleter',
     '~/plugins/vuexOrm.js',
+    { src: '~/plugins/sse.ts', mode: 'client' },
     '~/plugins/phone-input',
     '~/plugins/directives.js'
   ]

+ 15 - 0
plugins/sse.ts

@@ -0,0 +1,15 @@
+import {Plugin} from "@nuxt/types";
+import SseSource from "~/services/sse/sseSource";
+
+/**
+ * Setup SSE EventSource, allowing the app to listen for Mercure updates
+ * @param ctx
+ */
+const ssePlugin: Plugin = ({ $config, store }) => {
+  const sseSource = new SseSource($config.baseUrl_mercure, store.state.profile.access.id)
+
+  sseSource.subscribe()
+  window.addEventListener('beforeunload', () => { sseSource.unsubscribe() })
+}
+
+export default ssePlugin

+ 2 - 2
services/sse/sse.ts → services/sse/sseSource.ts

@@ -1,6 +1,6 @@
 import { EventSourcePolyfill } from "event-source-polyfill";
 
-class Sse {
+class SseSource {
   private readonly accessId: number
   private readonly url: URL
   private eventSource: EventSource | null = null
@@ -54,4 +54,4 @@ class Sse {
   }
 }
 
-export default Sse
+export default SseSource