Restructure

This commit is contained in:
Philipp Heckel 2022-02-20 16:55:55 -05:00
parent 8c0f3b2304
commit c6c3caec39
7 changed files with 6 additions and 13 deletions

View file

@ -0,0 +1,30 @@
import {topicUrl, shortTopicUrl, topicUrlWs} from './utils';
export default class Subscription {
id = '';
baseUrl = '';
topic = '';
notifications = [];
lastActive = null;
constructor(baseUrl, topic) {
this.id = topicUrl(baseUrl, topic);
this.baseUrl = baseUrl;
this.topic = topic;
}
addNotification(notification) {
if (notification.time === null) {
return;
}
this.notifications.push(notification);
this.lastActive = notification.time;
}
url() {
return this.id;
}
wsUrl() {
return topicUrlWs(this.baseUrl, this.topic);
}
shortUrl() {
return shortTopicUrl(this.baseUrl, this.topic);
}
}

View file

@ -0,0 +1,53 @@
export default class WsConnection {
id = '';
constructor(subscription, onNotification) {
this.id = subscription.id;
this.subscription = subscription;
this.onNotification = onNotification;
this.ws = null;
}
start() {
const socket = new WebSocket(this.subscription.wsUrl());
socket.onopen = (event) => {
console.log(this.id, "[open] Connection established");
}
socket.onmessage = (event) => {
console.log(this.id, `[message] Data received from server: ${event.data}`);
try {
const data = JSON.parse(event.data);
const relevantAndValid =
data.event === 'message' &&
'id' in data &&
'time' in data &&
'message' in data;
if (!relevantAndValid) {
return;
}
console.log('adding')
this.subscription.addNotification(data);
this.onNotification(this.subscription);
} catch (e) {
console.log(this.id, `[message] Error handling message: ${e}`);
}
};
socket.onclose = (event) => {
if (event.wasClean) {
console.log(this.id, `[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`);
} else {
console.log(this.id, `[close] Connection died`);
// e.g. server process killed or network down
// event.code is usually 1006 in this case
}
};
socket.onerror = (event) => {
console.log(this.id, `[error] ${event.message}`);
};
this.ws = socket;
}
cancel() {
if (this.ws != null) {
this.ws.close();
}
}
}

6
web/src/app/utils.js Normal file
View file

@ -0,0 +1,6 @@
export const topicUrl = (baseUrl, topic) => `${baseUrl}/${topic}`;
export const topicUrlWs = (baseUrl, topic) => `${topicUrl(baseUrl, topic)}/ws`
.replaceAll("https://", "wss://")
.replaceAll("http://", "ws://");
export const shortUrl = (url) => url.replaceAll(/https?:\/\//g, "");
export const shortTopicUrl = (baseUrl, topic) => shortUrl(topicUrl(baseUrl, topic));