Skip to content

Commit 7f97c03

Browse files
committed
PWA: create a WebSocket connection in the background at startup.
1 parent 3cca016 commit 7f97c03

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

pwa/src/index.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { createApp } from "vue";
22

33
import App from "./components/App.vue";
4+
import { ws } from "./ws";
45

56
if ("storage" in navigator && "persist" in navigator.storage) {
67
const isPersisted = await navigator.storage.persist();
@@ -15,4 +16,8 @@ if ("serviceWorker" in navigator) {
1516
});
1617
}
1718

18-
createApp(App).mount("#app");
19+
const app = createApp(App);
20+
21+
app.config.globalProperties["ws"] = ws;
22+
23+
app.mount("#app");

pwa/src/ws.ts

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import { state, store } from "@/store";
2+
3+
class WebSocketService {
4+
ws: WebSocket | null;
5+
6+
constructor() {
7+
this.ws = null;
8+
}
9+
10+
async init() {
11+
await store.ready;
12+
this.connect(new URL("ws", state.endpoint.value));
13+
}
14+
15+
connect(url: URL) {
16+
this.ws = new WebSocket(url);
17+
18+
this.ws.onopen = () => {
19+
console.log("[Websocket] Connected");
20+
};
21+
22+
this.ws.onclose = (event) => {
23+
const code = event.code;
24+
const reason = event.reason;
25+
const clean = event.wasClean ? "clean" : "not clean";
26+
console.log(`[WebSocket] Connection closed (${code}, "${reason}", ${clean})`);
27+
};
28+
29+
this.ws.onerror = (error) => {
30+
console.error("[WebSocket] Encountered error: ", error);
31+
};
32+
33+
this.ws.onmessage = (event) => {
34+
console.log("[WebSocket] Received message: ", event.data);
35+
};
36+
}
37+
}
38+
39+
export const ws = new WebSocketService();
40+
void ws.init();

0 commit comments

Comments
 (0)