Skip to content

Commit

Permalink
fix: Add changeUrl method to AutoReconnectingWebsocket
Browse files Browse the repository at this point in the history
  • Loading branch information
evrys committed Aug 1, 2024
1 parent ab1476b commit 2245ac5
Show file tree
Hide file tree
Showing 5 changed files with 49 additions and 11 deletions.
24 changes: 23 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@
"semantic-release": "^24.0.0",
"tsup": "^8.1.0",
"typescript": "^5.5.3",
"vitest": "^2.0.2"
"vitest": "^2.0.2",
"ws": "^8.18.0"
},
"dependencies": {
"@wandelbots/wandelbots-api-client": "^0.97.0",
Expand Down
25 changes: 17 additions & 8 deletions src/lib/AutoReconnectingWebsocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,6 @@ export class AutoReconnectingWebsocket extends ReconnectingWebSocket {
startClosed: true,
})

// reconnecting-websocket doesn't set this properly with startClosed
// so we do it ourselves
Object.defineProperty(this, "url", { value: url })

this.addEventListener("open", () => {
console.log(`Websocket to ${url} opened`)
})
Expand All @@ -25,11 +21,24 @@ export class AutoReconnectingWebsocket extends ReconnectingWebSocket {
console.log(`Websocket to ${url} closed`)
})

if (this.opts.mock) {
this.opts.mock.handleWebsocketConnection(this)
} else {
this.reconnect()
const origReconnect = this.reconnect
this.reconnect = () => {
if (this.opts.mock) {
this.opts.mock.handleWebsocketConnection(this)
} else {
this.reconnect()
}
origReconnect.apply(this)
}

this.changeUrl(url)
}

changeUrl(url: string) {
// reconnecting-websocket doesn't set this properly with startClosed
// so we do it ourselves
Object.defineProperty(this, "url", { value: url, configurable: true })
this.reconnect()
}

sendJson(data: unknown) {
Expand Down
2 changes: 2 additions & 0 deletions test/setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import ws from "ws"
globalThis.WebSocket = ws
6 changes: 5 additions & 1 deletion vitest.config.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
/// <reference types="vitest" />
import { defineConfig } from "vite"

export default defineConfig({})
export default defineConfig({
test: {
setupFiles: ["./test/setup.ts"],
},
})

0 comments on commit 2245ac5

Please sign in to comment.