Larry
05/24/2023, 10:00 PMconst testObject
is scoped to just the worker fetch handler. You can't even see it inside your queue handler. The second problem, that I suspect you will have is that even if you declare testObject before the start of the main worker fetch() handler so it's in scope, you have no guarantee that the worker instance that created the connection will be the same one as the one that's called by cloudflare via your queue() handler. It's best to think of these two pieces of code as completely seperate. Cloudflare will grabe them and instantiate them as needed. Once they are done running, they can disappear.
If you really have a good reason to use WebSockets from your queue() handler, you'll have to create the connection to the DO from inside there, but the only reason I can think of for doing that is that it might be slightly more efficient to make multiple round trips to a DO this way. For a single call though, the traditional way of talking to a DO is going to be more efficient because you don't have the handshake overhead of establishing the WebSocket connection. That said, it would be a premature optimization to even try this.