MWSE/Source/MessageRouter.js

55 lines
997 B
JavaScript

"use strict";
const handlers = new Map();
function register(type, handler) {
handlers.set(type, handler);
}
function handle(client, message) {
const { type } = message;
if (!type) {
return { status: 'fail', message: 'MISSING_TYPE' };
}
const handler = handlers.get(type);
if (!handler) {
return { status: 'fail', message: 'UNKNOWN_TYPE' };
}
try {
const result = handler(client, message);
return result;
} catch (error) {
console.error(`Handler error [${type}]:`, error);
return { status: 'fail', message: 'HANDLER_ERROR', error: error.message };
}
}
function unregister(type) {
handlers.delete(type);
}
function clear() {
handlers.clear();
}
function hasHandler(type) {
return handlers.has(type);
}
function listHandlers() {
return [...handlers.keys()];
}
module.exports = {
register,
handle,
unregister,
clear,
hasHandler,
listHandlers
};