chore(example) introduce changes to example implementation

This commit is contained in:
gh0sTedBuddy
2024-04-07 20:08:40 +01:00
parent 675ef2c5a7
commit cf279d4a3e
2 changed files with 34 additions and 48 deletions

View File

@@ -4,18 +4,18 @@ export default class WetSockClient {
this.listeners = new Map();
this.plugins = new Map();
this.socket.onopen = () => {
this.socket.addEventListener('open', () => {
console.log('Connected to WetSock server');
};
});
this.socket.onmessage = (event) => {
this.socket.addEventListener('message', (event) => {
const message = JSON.parse(event.data);
this.handleMessage(message);
};
});
this.socket.onclose = () => {
this.socket.addEventListener('close', () => {
console.log('Disconnected from WetSock server');
};
});
}
on(event, callback) {
@@ -33,13 +33,14 @@ export default class WetSockClient {
}
handleMessage(message) {
const { event, ...data } = message;
if (event === 'pluginList') {
this.updatePlugins(data.plugins);
} else {
this.emit(event, data);
this.emit('message', message);
const { event, data, ...rest } = message;
switch (event) {
case 'plugins':
this.updatePlugins(data);
break;
}
this.emit(event, data);
}
updatePlugins(plugins) {
@@ -49,34 +50,15 @@ export default class WetSockClient {
}
send(message) {
if(typeof(message) != 'string') throw new TypeError('message needs to be a string');
if(message.startsWith('/')) {
const [command, ...rest] = message.split(' ');
message = {
action: command.substring(1),
message: rest.join(' ')
}
}
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 ...
}