83 lines
1.9 KiB
JavaScript
83 lines
1.9 KiB
JavaScript
export default class WetSockClient {
|
|
constructor(url) {
|
|
this.socket = new WebSocket(url);
|
|
this.listeners = new Map();
|
|
this.plugins = new Map();
|
|
|
|
this.socket.onopen = () => {
|
|
console.log('Connected to WetSock server');
|
|
};
|
|
|
|
this.socket.onmessage = (event) => {
|
|
const message = JSON.parse(event.data);
|
|
this.handleMessage(message);
|
|
};
|
|
|
|
this.socket.onclose = () => {
|
|
console.log('Disconnected from WetSock server');
|
|
};
|
|
}
|
|
|
|
on(event, callback) {
|
|
if (!this.listeners.has(event)) {
|
|
this.listeners.set(event, []);
|
|
}
|
|
this.listeners.get(event).push(callback);
|
|
}
|
|
|
|
emit(event, ...args) {
|
|
const listeners = this.listeners.get(event);
|
|
if (listeners) {
|
|
listeners.forEach((listener) => listener(...args));
|
|
}
|
|
}
|
|
|
|
handleMessage(message) {
|
|
const { event, ...data } = message;
|
|
|
|
if (event === 'pluginList') {
|
|
this.updatePlugins(data.plugins);
|
|
} else {
|
|
this.emit(event, data);
|
|
}
|
|
}
|
|
|
|
updatePlugins(plugins) {
|
|
plugins.forEach((plugin) => {
|
|
this.plugins.set(plugin.identifier, plugin.actions);
|
|
});
|
|
}
|
|
|
|
send(message) {
|
|
this.socket.send(JSON.stringify(message));
|
|
}
|
|
|
|
// Generic methods for interacting with plugins
|
|
createEntity(pluginIdentifier, entityData) {
|
|
this.send({ action: 'create', pluginIdentifier, data: entityData });
|
|
}
|
|
|
|
performAction(pluginIdentifier, entityId, actionName, ...args) {
|
|
this.send({ action: 'perform', pluginIdentifier, entityId, data: { actionName, args } });
|
|
}
|
|
|
|
// Helper methods for common actions
|
|
joinRoom(roomId) {
|
|
this.performAction('room', roomId, 'join');
|
|
}
|
|
|
|
leaveRoom(roomId) {
|
|
this.performAction('room', roomId, 'leave');
|
|
}
|
|
|
|
sendMessageToRoom(roomId, message) {
|
|
this.performAction('room', roomId, 'sendMessage', message);
|
|
}
|
|
|
|
createTask(taskData) {
|
|
this.createEntity('task', taskData);
|
|
}
|
|
|
|
// ... other helper methods ...
|
|
}
|