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/Plugins/EntityPlugin.js

66 lines
1.8 KiB
JavaScript
Raw Normal View History

2024-04-02 15:57:41 +00:00
import BasePlugin from './BasePlugin';
class EntityPlugin extends BasePlugin {
#config = {};
#entities = new Map();
#repository = null;
constructor(config) {
super();
this.#config = config;
}
initialize(wetsock) {
super.initialize(wetsock);
this.#repository = this.#config.repository;
this.#config.entities.forEach((data) => {
const entity = this.#repository.create(data);
this.#entities.set(entity.id, entity);
});
}
onMessage(clientId, message) {
const { action, entityId, data } = message;
if (action === 'create') {
const entity = this.#repository.create(data);
this.#entities.set(entity.id, entity);
this.broadcast(clientId, { event: 'entityCreated', entityId: entity.id });
} else if (action === 'perform') {
const entity = this.#entities.get(entityId);
if (entity) {
const result = this.#repository.perform(entity, data.actionName, ...data.args);
this.broadcast(clientId, { event: 'actionPerformed', entityId, actionName: data.actionName, result });
}
}
}
onOpen(clientId) {
// Send the list of available entities to the client
const entityList = Array.from(this.#entities.values());
this.send(clientId, { event: 'entityList', entities: entityList });
}
onClose(clientId) {
// Handle client disconnection if needed
}
broadcast(clientId, message) {
// Broadcast the message to all connected clients
for (const [id, client] of this.#wetsock.clients) {
if (id !== clientId) {
client.send(JSON.stringify(message));
}
}
}
send(clientId, message) {
// Send the message to a specific client
const client = this.#wetsock.clients.get(clientId);
if (client) {
client.send(JSON.stringify(message));
}
}
}