Completed
Pull Request — master (#99)
by Ruben de
55s
created

rest_client.js ➔ RestClient   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
cc 3
c 2
b 0
f 1
nc 4
dl 0
loc 29
rs 8.8571
nop 1
1
var _ = require('lodash');
2
var Request = require('./request');
3
var q = require('q');
4
5
/**
6
 * Intermediate class to create HTTP requests
7
 *
8
 *
9
 * @param options       object{
10
 *                          host: '',
11
 *                          endpoint: '', // base url for .request
12
 *                          apiKey: 'API_KEY',
13
 *                          apiSecret: 'API_SECRET'
14
 *                      }
15
 * @constructor
16
 * @constructor
17
 */
18
var RestClient = function(options) {
19
    var self = this;
20
21
    self.apiKey = options.apiKey;
22
    self.apiSecret = options.apiSecret;
23
    self.https = options.https;
24
    self.host = options.host;
25
    self.port = options.port;
26
    self.endpoint = options.endpoint;
27
28
    self.btccom = !!options.btccom;
29
    if (self.btccom) {
30
        self.throttleRequestsTimeout = 1500;
31
    } else {
32
        self.throttleRequestsTimeout = 0;
33
    }
34
    self.throttleRequests = self.throttleRequestsTimeout > 0;
35
    self.nextRequest = null;
36
37
    self.defaultParams = {};
38
39
    if (self.apiKey) {
40
        self.defaultParams['api_key'] = self.apiKey;
41
    }
42
43
    self.defaultHeaders = _.defaults({}, {
44
        'X-SDK-Version': 'blocktrail-sdk-nodejs/' + require('./pkginfo').VERSION
45
    }, options.defaultHeaders);
46
};
47
48
RestClient.prototype.throttle = function() {
49
    var self = this;
50
    var deferred = q.defer();
51
52
    if (this.throttleRequests) {
53
        if (this.nextRequest) {
54
            // chain onto the previous delay
55
            this.nextRequest = this.nextRequest.then(function() {
56
                deferred.resolve();
57
58
                return q.delay(self.throttleRequestsTimeout);
59
            });
60
        } else {
61
            // first time we just resolve and setup the delay for the next request
62
            this.nextRequest = q.delay(self.throttleRequestsTimeout);
63
            deferred.resolve();
64
        }
65
    } else {
66
        deferred.resolve();
67
    }
68
69
    return deferred.promise;
70
};
71
72
RestClient.prototype.create_request = function(options) {
73
    var self = this;
74
75
    options = _.defaults({}, options, {
76
        https: self.https,
77
        host: self.host,
78
        port: self.port,
79
        endpoint: self.endpoint,
80
        apiKey: self.apiKey,
81
        apiSecret: self.apiSecret,
82
        params: _.defaults({}, self.defaultParams),
83
        headers: _.defaults({}, self.defaultHeaders)
84
    });
85
86
    return new Request(options);
87
};
88
89
RestClient.prototype.post = function(path, params, data, fn, requireAuth) {
90
    var self = this;
91
92
    requireAuth = typeof requireAuth === "undefined" ? true : requireAuth;
93
94
    var options = {};
95
    if (requireAuth) {
96
        options['auth'] = 'http-signature';
97
    }
98
99
    return self.throttle().then(function() {
100
        return self.create_request(options).request('POST', path, params, data, fn);
101
    });
102
};
103
104
RestClient.prototype.put = function(path, params, data, fn, requireAuth) {
105
    var self = this;
106
107
    requireAuth = typeof requireAuth === "undefined" ? true : requireAuth;
108
109
    var options = {};
110
    if (requireAuth) {
111
        options['auth'] = 'http-signature';
112
    }
113
114
    return self.throttle().then(function() {
115
        return self.create_request(options).request('PUT', path, params, data, fn);
116
    });
117
};
118
119
RestClient.prototype.get = function(path, params, doHttpSignature, fn) {
120
    var self = this;
121
122
    if (typeof doHttpSignature === "function") {
123
        fn = doHttpSignature;
124
        doHttpSignature = false;
125
    }
126
127
    var options = {};
128
129
    if (doHttpSignature) {
130
        options['auth'] = 'http-signature';
131
    }
132
133
    if (self.btccom && typeof fn !== "undefined") {
134
        throw new Error("we should be using callbackify!");
135
    }
136
137
    return self.throttle().then(function() {
138
        return self.create_request(options).request('GET', path, params, null, fn);
139
    });
140
};
141
142
RestClient.prototype.delete = function(path, params, data, fn, requireAuth) {
143
    var self = this;
144
145
    requireAuth = typeof requireAuth === "undefined" ? true : requireAuth;
146
147
    var options = {};
148
    if (requireAuth) {
149
        options['auth'] = 'http-signature';
150
    }
151
152
    return self.throttle().then(function() {
153
        return self.create_request(options).request('DELETE', path, params, data, fn);
154
    });
155
};
156
157
module.exports = function(options) {
158
    return new RestClient(options);
159
};
160