Authoring queries over HTTP come with an inherit overhead on each request when you include all of the request headers and metadata that is sent each time. Web sockets on the other hand allow you to open up a long-living connection between the client and the server where each time you need to make a new request, no overhead of header data (such as Content-Type
or Authorization
, etc) is required for each transaction. Instead you can just send an object that details what type of action you’re looking to perform, and then wait for your result to be returned back to you.
Establishing Connections
You can open up a web socket connection to your StarbaseDB instance by first attempting to authorize your credentials with the server via an WSS request, and then establishing a WebSocket
object in your code.
To authorize you have the correct privileges to establish a tunnel you must first send a request to the /socket?token=XXXXX
endpoint where the token
value matches your AUTHORIZATION_TOKEN
value from your wrangler.toml file. If you provide a successful match then you will have an agreed handshake via the response where you can then follow up with issuing queries from it.
socket = new WebSocket('wss://starbasedb.YOUR-IDENTIFIER.dev/socket?token=ABC123');
socket.onopen = function() {
logMessage("WebSocket connection opened.");
};
socket.onmessage = function(event) {
logMessage("Received: " + event.data);
};
socket.onclose = function(event) {
logMessage(`WebSocket closed with code: ${event.code}, reason: ${event.reason}, clean: ${event.wasClean}`);
};
socket.onerror = function(error) {
logMessage("WebSocket error: " + error.message);
};