This is the template project that's checked out and configured when you run the bando-up command from ljsthw-bandolier. This is where the code really lives.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
bandolier-template/client/websocket.js

51 lines
1.4 KiB

/*
Helpers for dealing with the `socket/` handlers, similar to the
code in `client/api.js`. WebSockets already work well with JSON
data, so this mostly handles create a single connection, and
reconnecting when you need to.
*/
import { inject_remote } from "$/client/components/Source.svelte";
let raw_socket;
/*
Load the `/js/socket.io.min.js` file using `client/components/Sourse.svelte:inject_remote`.
This makes it so if you don't use the socket.io stuff then you won't download the code.
*/
export const configure_socket = async () => {
await inject_remote(document, "/js/socket.io.min.js");
}
/*
Connect to the server __once__. This should maintain the connection
in the SPA for as long as possible and return only one.
+ `reconnection boolean` -- The reconnection policy that's passed to socket.io `io()`.
*/
export const connect_socket = (reconnection=false) => {
if(raw_socket === undefined) {
raw_socket = io({ reconnection });
}
return raw_socket;
}
/*
This is actually the way you should connect a socket in most pages.
This will detect if a connection already exists, and if it does it
simply disconnects, then reconnects.
If there isn't a connection yet then it will call `connect_socket()`
to establish the first one.
*/
export const reconnect_socket = () => {
if(raw_socket !== undefined) {
raw_socket.disconnect();
raw_socket.connect();
} else {
connect_socket();
}
return raw_socket;
}