This repository has been archived on 2025-03-10. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
wetsock/lib/WetSock/WetSock.js

55 lines
1.3 KiB
JavaScript
Raw Normal View History

2024-04-02 15:57:41 +00:00
export default class WetSock {
#config = undefined;
#server = undefined;
#clients = new Map();
#plugins = new Map();
constructor(config) {
this.config = config;
this.server = null;
}
start(server) {
this.#server = server;
}
registerPlugin(identifier, plugin) {
plugin.initialize(this);
this.#plugins.set(identifier, plugin);
}
getPlugin(identifier) {
return this.#plugins.get(identifier);
}
handleUpgrade(req) {
const clientId = Math.random().toString(36).substring(2);
const success = this.#server.upgrade(req, { data: { clientId } });
if (success) {
return undefined;
}
return Response.redirect('/', 302);
}
handleMessage(ws, message) {
const client = this.#clients.get(ws.data.clientId);
for(const plugin of this.#plugins) {
if(plugin.onMessage(ws.data.clientId, message)) break; // plugin consumes message by returning a truthy value
}
}
handleOpen(ws) {
const client = this.#clients.get(ws.data.clientId);
this.#plugins.forEach((plugin) => plugin.onOpen(ws.data.clientId));
}
handleClose(ws) {
const client = this.#clients.get(ws.data.clientId);
this.#plugins.forEach((plugin) => plugin.onClose(ws.data.clientId));
this.#clients.delete(ws.data.clientId);
}
handleDrain(ws) {
// Handle socket drain event
}
}