diff --git a/src/main.ts b/src/main.ts index 546cffa..3a93db1 100644 --- a/src/main.ts +++ b/src/main.ts @@ -8,6 +8,7 @@ import { import striptags from "striptags"; import { PrismaClient } from "../generated/prisma/client.js"; import { createWebsocket } from "./websocket.js"; +import { WebSocket } from "ws"; const prisma = new PrismaClient(); @@ -153,16 +154,29 @@ const postReplyToStatus = async ( let ws = createWebsocket(); +const reconnect = (ws: WebSocket) => { + if (ws) { + ws.close(); + } + return createWebsocket(); +}; + +ws.on("close", () => { + for (let i = 0; i < 5; i++) { + if (ws.readyState !== WebSocket.OPEN) { + setTimeout(() => { + ws = reconnect(ws); + }, 5000); + } + } +}); + ws.on("upgrade", () => { console.log( `Websocket connection to ${process.env.PLEROMA_INSTANCE_DOMAIN} successful.` ); }); -ws.on("close", (event: CloseEvent) => { - console.log(`Connection closed: ${event.reason}`); -}); - ws.on("open", () => { setInterval(() => { ws.send(JSON.stringify({ type: "ping" }));