-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
7f8d416
commit 05346a4
Showing
3 changed files
with
15 additions
and
13 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,23 +1,25 @@ | ||
let socket: WebSocket | null = null; | ||
let socket: WebSocket | undefined; | ||
|
||
const startWebsocket = (url: string, messageHandler: Function): void => { | ||
type handler = (message: Record<string, unknown>) => void; | ||
|
||
const startWebsocket = (url: string, messageHandler: handler): void => { | ||
if (socket) return; | ||
socket = new WebSocket(url); | ||
socket.onmessage = event => { | ||
socket.addEventListener('message', event => { | ||
const jsonMessage = JSON.parse(event.data); | ||
messageHandler(jsonMessage); | ||
}; | ||
socket.onclose = event => { | ||
console.log('Websocket connection closed with reason: ', event); | ||
socket = null; | ||
}; | ||
}); | ||
socket.addEventListener('close', event => { | ||
console.log('Websocket connection closed with reason: ' + event); | ||
socket = undefined; | ||
}); | ||
}; | ||
|
||
const sendMessage = (message: string): void => socket?.send(JSON.stringify(message)); | ||
|
||
const closeSocket = () => { | ||
socket?.close(); | ||
socket = null; | ||
socket = undefined; | ||
}; | ||
|
||
export { startWebsocket, sendMessage, closeSocket }; |