all files / src/message/ message.dispatcher.js

94.74% Statements 18/19
95.45% Branches 21/22
100% Functions 4/4
94.74% Lines 18/19
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92                                  15×     12× 12×             12×                                                                                                  
/**
 * Class represents MessageDispatcher
 */
class MessageDispatcher {
 
    /**
     * creates new MessageDispatcher instance
     * @param {object} actionAllocator
     */
    constructor(actionAllocator = null) {
        this._actionAllocator = actionAllocator;
        this._filter = null;
    }
 
    /**
     * handles and maps incoming messages
     * @param {Message} message
     */
    onMessage(message) {
        if(!message) {
            return false;
        }
 
        const action = message.getAction();
        const allocatorType = (
            this._actionAllocator &&
            typeof this._actionAllocator === 'object'
        )
            ? typeof this._actionAllocator[action]
            : null;
 
        if(
            !allocatorType ||
            (
                typeof this._filter === 'function' &&
                !this._filter(message.getData())
            )
        ) {
            return;
        }
 
        switch (allocatorType) {
            case 'function':
                return this._actionAllocator[action](message.getData());
            case 'object':
                return this._runObjectAllocator(this._actionAllocator[action], message.getData());
            default:
            // ignore
                break;
        }
 
    }
 
    /**
     * run against object allocator
     * @param {object} allocator
     * @param {Message.data} data
     * @private
     */
    _runObjectAllocator(allocator, data) {
        const hasFn = (typeof allocator.fn === 'function');
        const hasFilter = (typeof allocator.filter === 'function');
 
        Iif(
            !hasFn ||
            (
                hasFilter &&
                !allocator.filter(data)
            )
        ) {
            return null;
        } else {
            return allocator.fn(data);
        }
 
    }
 
    /**
     * define general filter for this dispatcher
     * @param {function} filterMethod
     * @return {MessageDispatcher}
     */
    filter(filterMethod) {
        this._filter = (typeof filterMethod === 'function') ? filterMethod : null;
        return this;
    }
 
}
 
export {
    MessageDispatcher,
};