shoehive
Version:
WebSocket-based multiplayer game framework for real-time, event-driven gameplay
55 lines (54 loc) • 2.07 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.MessageRouter = void 0;
const index_1 = require("../core/commands/index");
class MessageRouter {
constructor(eventBus) {
this.eventBus = eventBus;
this.commandHandlers = new Map();
}
/**
* Register a command handler for a specific action. For example, if you
* want a user to be able to make a choice, you could register `game:choice:make`
* and then handle it in your game logic.
* @param action - The action to register the handler for
* @param handler - The handler function to be called when the action is received
*/
registerCommandHandler(action, handler) {
this.commandHandlers.set(action, handler);
}
/**
* Process a message from the client.
* @param player - The player object
* @param messageStr - The message string to process
*/
processMessage(player, messageStr) {
try {
const message = JSON.parse(messageStr);
// Validate message format
if (!message.action || typeof message.action !== "string") {
player.sendMessage({
type: index_1.CLIENT_MESSAGE_TYPES.ERROR,
message: "Invalid message format: missing or invalid action"
});
return;
}
// First check if we have a registered command handler for this action
const handler = this.commandHandlers.get(message.action);
if (handler) {
handler(player, message);
return;
}
// Otherwise, treat it as an event
this.eventBus.emit(message.action, player, message);
}
catch (error) {
console.error("Error processing message:", error);
player.sendMessage({
type: index_1.CLIENT_MESSAGE_TYPES.ERROR,
message: "Failed to process message"
});
}
}
}
exports.MessageRouter = MessageRouter;