Auto reconnect to Mastodon WebSocket if it fails

This commit is contained in:
Max Nuding 2023-04-15 09:56:03 +02:00
parent 52c7922002
commit 45eeb550b3
Signed by: phlaym
GPG Key ID: A06651BAB6777237

View File

@ -78,7 +78,7 @@ export class TimelineReader {
return false; return false;
} }
private constructor() { private startWebsocket() {
const socket = new WebSocket(`wss://${MASTODON_INSTANCE}/api/v1/streaming`); const socket = new WebSocket(`wss://${MASTODON_INSTANCE}/api/v1/streaming`);
socket.onopen = () => { socket.onopen = () => {
socket.send('{ "type": "subscribe", "stream": "public:local"}'); socket.send('{ "type": "subscribe", "stream": "public:local"}');
@ -113,13 +113,25 @@ export class TimelineReader {
} }
}; };
socket.onclose = (event) => { socket.onclose = (event) => {
console.log('Closed', event, event.code, event.reason); console.warn(
`Websocket connection to ${MASTODON_INSTANCE} closed. Code: ${event.code}, reason: '${event.reason}'`
);
setTimeout(() => {
console.info(`Attempting to reconenct to WS`);
this.startWebsocket();
}, 10000);
}; };
socket.onerror = (event) => { socket.onerror = (event) => {
console.log('error', event, event.message, event.error); console.error(
`Websocket connection to ${MASTODON_INSTANCE} failed. ${event.type}: ${event.error}, message: '${event.message}'`
);
}; };
} }
private constructor() {
this.startWebsocket();
}
public static init() { public static init() {
if (this._instance === undefined) { if (this._instance === undefined) {
this._instance = new TimelineReader(); this._instance = new TimelineReader();