1
0
Fork 0
mirror of synced 2024-09-20 11:27:56 +12:00
budibase/packages/frontend-core/src/utils/websocket.js

42 lines
1.2 KiB
JavaScript
Raw Normal View History

2023-05-17 01:18:31 +12:00
import { io } from "socket.io-client"
import { SocketEvents, SocketSessionTTL } from "@budibase/shared-core"
2023-05-17 01:18:31 +12:00
export const createWebsocket = (path, heartbeat = true) => {
2023-05-17 01:18:31 +12:00
if (!path) {
throw "A websocket path must be provided"
}
// Determine connection info
const tls = location.protocol === "https:"
const proto = tls ? "wss:" : "ws:"
const host = location.hostname
const port = location.port || (tls ? 443 : 80)
const socket = io(`${proto}//${host}:${port}`, {
2023-05-17 01:18:31 +12:00
path,
// Cap reconnection attempts to 3 (total of 15 seconds before giving up)
reconnectionAttempts: 3,
// Delay reconnection attempt by 5 seconds
reconnectionDelay: 5000,
reconnectionDelayMax: 5000,
// Timeout after 4 seconds so we never stack requests
timeout: 4000,
// Disable polling and rely on websocket only, as HTTP transport
// will only work with sticky sessions which we don't have
transports: ["websocket"],
2023-05-17 01:18:31 +12:00
})
// Set up a heartbeat that's half of the session TTL
let interval
if (heartbeat) {
interval = setInterval(() => {
socket.emit(SocketEvents.Heartbeat)
}, SocketSessionTTL * 500)
}
socket.on("disconnect", () => {
clearInterval(interval)
})
return socket
2023-05-17 01:18:31 +12:00
}