Puts the sending event function into a separate thread form the onOpen

This commit is contained in:
Vitor Pamplona 2023-09-05 09:25:07 -04:00
parent 24fb5af10f
commit 48853d9f1c

View File

@ -178,6 +178,13 @@ function hexToBytes(hex) {
return Object.keys(events).map((id) => events[id]) return Object.keys(events).map((id) => events[id])
} }
const sendAllEvents = async (relay, data, relayStatus, ws) => {
console.log("Sending:", data.length, " events")
for (evnt of data) {
ws.send(JSON.stringify(['EVENT', evnt]))
}
}
// send events to a relay, returns a promisse // send events to a relay, returns a promisse
const sendToRelay = async (relay, data, relayStatus) => const sendToRelay = async (relay, data, relayStatus) =>
new Promise((resolve, reject) => { new Promise((resolve, reject) => {
@ -195,15 +202,14 @@ function hexToBytes(hex) {
// fetch events from relay // fetch events from relay
ws.onopen = () => { ws.onopen = () => {
updateRelayStatus(relay, "Sending", 0, relayStatus) updateRelayStatus(relay, "Sending", 0, relayStatus)
for (evnt of data) {
clearTimeout(myTimeout) clearTimeout(myTimeout)
myTimeout = setTimeout(() => { myTimeout = setTimeout(() => {
ws.close() ws.close()
reject('timeout') reject('timeout')
}, 10_000) }, 10_000)
ws.send(JSON.stringify(['EVENT', evnt])) sendAllEvents(relay, data, relayStatus, ws)
}
} }
// Listen for messages // Listen for messages
ws.onmessage = (event) => { ws.onmessage = (event) => {
@ -222,6 +228,8 @@ function hexToBytes(hex) {
} else { } else {
console.log(event.data) console.log(event.data)
} }
} else {
console.log(event.data)
} }
} }
ws.onerror = (err) => { ws.onerror = (err) => {
@ -232,6 +240,7 @@ function hexToBytes(hex) {
} }
ws.onclose = (socket, event) => { ws.onclose = (socket, event) => {
updateRelayStatus(relay, "Done", 0, relayStatus) updateRelayStatus(relay, "Done", 0, relayStatus)
console.log("OnClose", relayStatus)
resolve() resolve()
} }
} catch (exception) { } catch (exception) {