Code coverage report for web3/lib/web3/subscription.js

Statements: 83.93% (47 / 56)      Branches: 68.57% (24 / 35)      Functions: 84.62% (11 / 13)      Lines: 83.93% (47 / 56)      Ignored: none     

All files » web3/lib/web3/ » subscription.js
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 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196                                              1 1     1 10 10   10                                 1 10 10                       1 10   10 4   10 4   10                         1 10   10 5     5 5   5   5                     1 7   7                   1 10 10 10   10                       1 6                 1 10 10     10         10                               10   10 9 9     9 7               10           1
/*
    This file is part of web3.js.
 
    web3.js is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
 
    web3.js is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.
 
    You should have received a copy of the GNU Lesser General Public License
    along with web3.js.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file subscription.js
 *
 * @authors:
 *   Fabian Vogelsteller <fabian@ethdev.com>
 * @date 2015
 */
 
var utils = require('../utils/utils');
var errors = require('./errors');
 
 
Subscription = function (options) {
    this.id = null;
    this.callback = null;
 
    this.options = {
        subscription: options.subscription,
        subscribeMethod: options.subscribeMethod,
        unsubscribeMethod: options.unsubscribeMethod,
        requestManager: options.requestManager
    }
};
 
 
/**
 * Should be used to extract callback from array of arguments. Modifies input param
 *
 * @method extractCallback
 * @param {Array} arguments
 * @return {Function|Null} callback, if exists
 */
 
Subscription.prototype._extractCallback = function (args) {
    Eif (utils.isFunction(args[args.length - 1])) {
        return args.pop(); // modify the args array!
    }
};
 
/**
 * Should be called to check if the number of arguments is correct
 * 
 * @method validateArgs
 * @param {Array} arguments
 * @throws {Error} if it is not
 */
 
Subscription.prototype._validateArgs = function (args) {
    var subscription = this.options.subscription;
 
    if(!subscription)
        subscription = {};
 
    if(!subscription.params)
        subscription.params = 0;
 
    Iif (args.length !== subscription.params + 1) {
        throw errors.InvalidNumberOfParams();
    }
};
 
/**
 * Should be called to format input args of method
 * 
 * @method formatInput
 * @param {Array}
 * @return {Array}
 */
 
Subscription.prototype._formatInput = function (args) {
    var subscription = this.options.subscription;
 
    if (!subscription || !subscription.inputFormatter) {
        return args;
    }
 
    var formattedArgs = subscription.inputFormatter.map(function (formatter, index) {
        return formatter ? formatter(args[index+1]) : args[index+1];
    });
    formattedArgs.unshift(args[0]);
 
    return formattedArgs;
};
 
/**
 * Should be called to format output(result) of method
 *
 * @method formatOutput
 * @param {Object}
 * @return {Object}
 */
 
Subscription.prototype._formatOutput = function (result) {
    var subscription = this.options.subscription;
 
    return (subscription && subscription.outputFormatter && result) ? subscription.outputFormatter(result) : result;
};
 
/**
 * Should create payload from given input args
 *
 * @method toPayload
 * @param {Array} args
 * @return {Object}
 */
Subscription.prototype._toPayload = function (args) {
    this.callback = this._extractCallback(args);
    var params = this._formatInput(args);
    this._validateArgs(params);
 
    return {
        method: this.options.subscribeMethod,
        params: params
    };
};
 
/**
 * Unsubscribes and clears callbacks
 *
 * @method unsubscribe
 * @return {Object}
 */
Subscription.prototype.unsubscribe = function(callback) {
    return this.options.requestManager.removeSubscription(this.id, callback);
};
 
/**
 * Subscribes and watches for changes
 *
 * @method subscribe
 * @return {Object}
 */
Subscription.prototype.subscribe = function() {
    var _this = this;
    var payload = this._toPayload(Array.prototype.slice.call(arguments));
 
    // throw error, if provider doesnt support subscriptions
    Iif(!this.options.requestManager.provider.on)
        throw new Error('The current provider doesn\'t support subscriptions', this.options.requestManager.provider);
 
 
    // get past logs, if fromBlock is available
    Iif(payload.params[0] === 'logs' && utils.isObject(payload.params[1]) && payload.params[1].hasOwnProperty('fromBlock') && isFinite(payload.params[1].fromBlock)) {
        this.options.requestManager.sendAsync({
            method: 'eth_getLogs',
            params: [payload.params[1]]
        }, function (err, logs) {
            if(!err) {
                logs.forEach(function(log){
                    _this.callback(null, _this._formatOutput(log));
                });
            } else {
                _this.callback(err);
            }
        });
    }
 
    // create subscription
    Eif (_this.callback) {
 
        this.options.requestManager.sendAsync(payload, function (err, result) {
            Eif(!err && result) {
                _this.id = result;
                
                // call callback on notifications
                _this.options.requestManager.addSubscription('eth', _this.id, function(err, result){
                    _this.callback(err, _this._formatOutput(result), _this);
                });
            } else {
                _this.callback(err);
            }
        });
 
        // return an object to cancel the subscription
        return this;
 
    } else
        throw new Error('Subscriptions require a callback as the last parameter!');
};
 
module.exports = Subscription;