* @param {string} url url * @param {{ [handler: string]: (data?: EXPECTED_ANY, params?: EXPECTED_ANY) => EXPECTED_ANY }} handlers handlers * @param {number=} reconnect count of reconnections
(url, handlers, reconnect)
| 39 | * @param {number=} reconnect count of reconnections |
| 40 | */ |
| 41 | function socket(url, handlers, reconnect) { |
| 42 | client = new Client(url); |
| 43 | |
| 44 | client.onOpen(() => { |
| 45 | retries = 0; |
| 46 | |
| 47 | if (timeout) { |
| 48 | clearTimeout(timeout); |
| 49 | } |
| 50 | |
| 51 | if (typeof reconnect !== "undefined") { |
| 52 | maxRetries = reconnect; |
| 53 | } |
| 54 | }); |
| 55 | |
| 56 | client.onClose(() => { |
| 57 | if (retries === 0) { |
| 58 | handlers.close(); |
| 59 | } |
| 60 | |
| 61 | // Try to reconnect. |
| 62 | client = null; |
| 63 | |
| 64 | // After 10 retries stop trying, to prevent logspam. |
| 65 | if (retries < maxRetries) { |
| 66 | // Exponentially increase timeout to reconnect. |
| 67 | // Respectfully copied from the package `got`. |
| 68 | const retryInMs = 1000 * Math.pow(2, retries) + Math.random() * 100; |
| 69 | |
| 70 | retries += 1; |
| 71 | |
| 72 | log.info("Trying to reconnect..."); |
| 73 | |
| 74 | timeout = setTimeout(() => { |
| 75 | socket(url, handlers, reconnect); |
| 76 | }, retryInMs); |
| 77 | } |
| 78 | }); |
| 79 | |
| 80 | client.onMessage( |
| 81 | /** |
| 82 | * @param {EXPECTED_ANY} data data |
| 83 | */ |
| 84 | (data) => { |
| 85 | const message = JSON.parse(data); |
| 86 | |
| 87 | if (handlers[message.type]) { |
| 88 | handlers[message.type](message.data, message.params); |
| 89 | } |
| 90 | }, |
| 91 | ); |
| 92 | } |
| 93 | |
| 94 | export default socket; |