All files / web3-core-requestmanager/src index.js

84.21% Statements 64/76
75.36% Branches 52/69
84.62% Functions 11/13
85.33% Lines 64/75
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 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245                                                  1x 1x 1x 1x 1x                   1x 4129x 4129x   4129x 4129x         1x   1x                           1x 8008x     8008x     116x 36x     80x 36x     44x 36x   8x 8x         8000x 81x     8000x     8000x 2372x 1164x 1096x 165x     68x                                 1x 572x   572x       572x 572x 572x   572x 3x     569x       569x 7x     562x                     1x 4x       4x 4x 4x       4x       4x                           1x 37x 37x                                   1x 36x   36x   36x           36x                 1x 81x       81x             81x       1x          
/*
    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 index.js
 * @author Fabian Vogelsteller <fabian@ethereum.org>
 * @date 2017
 */
 
"use strict";
 
 
var _ = require('underscore');
var errors = require('web3-core-helpers').errors;
var Jsonrpc = require('./jsonrpc.js');
var BatchManager = require('./batch.js');
var givenProvider = require('./givenProvider.js');
 
 
 
    /**
 * It's responsible for passing messages to providers
 * It's also responsible for polling the ethereum node for incoming messages
 * Default poll timeout is 1 second
 * Singleton
 */
var RequestManager = function RequestManager(provider) {
    this.provider = null;
    this.providers = RequestManager.providers;
 
    this.setProvider(provider);
    this.subscriptions = {};
};
 
 
 
RequestManager.givenProvider = givenProvider;
 
RequestManager.providers = {
    WebsocketProvider: require('web3-providers-ws'),
    HttpProvider: require('web3-providers-http'),
    IpcProvider: require('web3-providers-ipc')
};
 
 
 
/**
 * Should be used to set provider of request manager
 *
 * @method setProvider
 * @param {Object} p
 */
RequestManager.prototype.setProvider = function (p, net) {
    var _this = this;
 
    // autodetect provider
    if(p && typeof p === 'string' && this.providers) {
 
        // HTTP
        if(/^http(s)?:\/\//i.test(p)) {
            p = new this.providers.HttpProvider(p);
 
            // WS
        } else if(/^ws(s)?:\/\//i.test(p)) {
            p = new this.providers.WebsocketProvider(p);
 
            // IPC
        } else if(p && typeof net === 'object'  && typeof net.connect === 'function') {
            p = new this.providers.IpcProvider(p, net);
 
        } else Eif(p) {
            throw new Error('Can\'t autodetect provider for "'+ p +'"');
        }
    }
 
    // reset the old one before changing
    if(this.provider)
        this.clearSubscriptions();
 
 
    this.provider = p || null;
 
    // listen to incoming notifications
    if(this.provider && this.provider.on) {
        this.provider.on('data', function requestManagerNotification(err, result){
            if(!err) {
                if(_this.subscriptions[result.params.subscription] && _this.subscriptions[result.params.subscription].callback)
                    _this.subscriptions[result.params.subscription].callback(null, result.params.result);
            } else {
 
                Object.keys(_this.subscriptions).forEach(function(id){
                    if(_this.subscriptions[id].callback)
                        _this.subscriptions[id].callback(err);
                });
            }
        });
    }
};
 
 
/**
 * Should be used to asynchronously send request
 *
 * @method sendAsync
 * @param {Object} data
 * @param {Function} callback
 */
RequestManager.prototype.send = function (data, callback) {
    callback = callback || function(){};
 
    Iif (!this.provider) {
        return callback(errors.InvalidProvider());
    }
 
    var payload = Jsonrpc.toPayload(data.method, data.params);
    this.provider[this.provider.sendAsync ? 'sendAsync' : 'send'](payload, function (err, result) {
        Iif(result && result.id && payload.id !== result.id) return callback(new Error('Wrong response id "'+ result.id +'" (expected: "'+ payload.id +'") in '+ JSON.stringify(payload)));
 
        if (err) {
            return callback(err);
        }
 
        Iif (result && result.error) {
            return callback(errors.ErrorResponse(result));
        }
 
        if (!Jsonrpc.isValidResponse(result)) {
            return callback(errors.InvalidResponse(result));
        }
 
        callback(null, result.result);
    });
};
 
/**
 * Should be called to asynchronously send batch request
 *
 * @method sendBatch
 * @param {Array} batch data
 * @param {Function} callback
 */
RequestManager.prototype.sendBatch = function (data, callback) {
    Iif (!this.provider) {
        return callback(errors.InvalidProvider());
    }
 
    var payload = Jsonrpc.toBatchPayload(data);
    this.provider.send(payload, function (err, results) {
        Iif (err) {
            return callback(err);
        }
 
        Iif (!_.isArray(results)) {
            return callback(errors.InvalidResponse(results));
        }
 
        callback(null, results);
    });
};
 
 
/**
 * Waits for notifications
 *
 * @method addSubscription
 * @param {String} id           the subscription id
 * @param {String} name         the subscription name
 * @param {String} type         the subscription namespace (eth, personal, etc)
 * @param {Function} callback   the callback to call for incoming notifications
 */
RequestManager.prototype.addSubscription = function (id, name, type, callback) {
    Eif(this.provider.on) {
        this.subscriptions[id] = {
            callback: callback,
            type: type,
            name: name
        };
 
    } else {
        throw new Error('The provider doesn\'t support subscriptions: '+ this.provider.constructor.name);
    }
};
 
/**
 * Waits for notifications
 *
 * @method removeSubscription
 * @param {String} id           the subscription id
 * @param {Function} callback   fired once the subscription is removed
 */
RequestManager.prototype.removeSubscription = function (id, callback) {
    var _this = this;
 
    Eif(this.subscriptions[id]) {
 
        this.send({
            method: this.subscriptions[id].type + '_unsubscribe',
            params: [id]
        }, callback);
 
        // remove subscription
        delete _this.subscriptions[id];
    }
};
 
/**
 * Should be called to reset the subscriptions
 *
 * @method reset
 */
RequestManager.prototype.clearSubscriptions = function (keepIsSyncing) {
    var _this = this;
 
 
    // uninstall all subscriptions
    Object.keys(this.subscriptions).forEach(function(id){
        if(!keepIsSyncing || _this.subscriptions[id].name !== 'syncing')
            _this.removeSubscription(id);
    });
 
 
    //  reset notification callbacks etc.
    Iif(this.provider.reset)
        this.provider.reset();
};
 
module.exports = {
    Manager: RequestManager,
    BatchManager: BatchManager
};