Migrate to Websocket Hibernation API
I have some code already working on my Worker, with Durable Objects and standard Websockets.
However, due to the high costs, I am trying to migrate to the Websocket Hibernation API.
What I did, following the documentation: I removed the "message" and "close" listeners and used
webSocketMessage()
and webSocketClose()
, and also changed server.accept()
to this.state.acceptWebSocket(server)
However, my original code had a few extra actions.
For example, I had an element this.firstConnection = null
in the constructor, which, when opening a new connection, saved this connection in this.firstConnection
, since it is necessary to send messages directly to the first Websocket connection and I am not able to do this using the Hibernation API.
I tried to do it like this now, right after acceptWebSocket() in async fetch(request)
if (!this.firstConnection) {
this.firstConnection = server;
} else {
if (this.firstConnection.readyState === WebSocket.OPEN) {
this.firstConnection.send(
JSON.stringify({ Event: "sync", Command: "" })
);
console.log("Event 'sync' send to the first Connection");
}
}
I think that Websocket clients in the Hibernation API should be accessed in another way, but I can't find anything about this in the documentation.
The code I wrote above, for example, doesn't work, apparently, it doesn't save the state of the first connection.0 Replies