127.0.0.1:8000 watch-together / master server / websocket / onmessage.js
master

Tree @master (Download .tar.gz)

onmessage.js @masterraw · history · blame

const path = require('path');
const fs = require('fs');

const handlers = fs.readdirSync(
    path.join(__dirname, "messages")
).reduce(function(acc, command) {
    if (path.extname(command) === ".js") {
        command = command.substr(0, command.length - 3);
        console.log("create wss message handler", command)
        return Object.assign(acc, {
            [command]: function(ws, user_id, data) {
                require('./messages/' + command)(user_id, data, function(data) {
                    ws.send(JSON.stringify({
                        command: command + "-response",
                        data: data
                    }));
                });
            }
        });
    } else {
        return acc;
    }
}, {});

module.exports = {
    handlers: handlers,
    process: function(ws, user_id, message) {
        // console.log("WS - process", message.command, "from", user_id);
        handlers[message.command](ws, user_id, message.data);
    }
};