-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathindex.js
More file actions
142 lines (116 loc) · 3.6 KB
/
index.js
File metadata and controls
142 lines (116 loc) · 3.6 KB
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
'use strict';
const transform = require('lodash/transform');
const defaults = require('lodash/defaults');
const assign = require('lodash/assign');
const EventEmitter = require('events');
const stopcock = require('stopcock');
const got = require('got');
const urlLib = require('url');
const pkg = require('./package');
const resources = require('./resources');
function Recharge(options){
if (!(this instanceof Recharge)) return new Recharge(options);
if (
!options ||
!options.apiKey || !options.secrete
) {
throw new Error('Missing or invalid options');
}
EventEmitter.call(this);
this.options = defaults(options, { timeout: 60000 });
//
// API call limits, updated with each request.
//
this.callLimits = {
remaining: undefined,
current: undefined,
max: undefined
};
this.baseUrl = {
headers: {
'X-Recharge-Access-Token': options.apiKey
},
hostname: 'api.rechargeapps.com',
protocol: 'https:'
};
// handle api threshold
if (options.autoLimit) {
const conf = transform(options.autoLimit, (result, value, key) => {
if (key === 'calls') key = 'limit';
result[key] = value;
}, { bucketSize: 35 });
this.request = stopcock(this.request, conf);
}
}
Object.setPrototypeOf(Recharge.prototype, EventEmitter.prototype);
/**
* Updates API call limits.
*
* @param {String} header X-Recharge-Limit header
* @private
*/
Recharge.prototype.updateLimits = function updateLimits(header) {
if (!header) return;
const limits = header.split('/').map(Number);
const callLimits = this.callLimits;
callLimits.remaining = limits[1] - limits[0];
callLimits.current = limits[0];
callLimits.max = limits[1];
this.emit('callLimits', callLimits);
};
/**
* Sends a request to a Recharge API endpoint.
*
* @param {Object} url URL object
* @param {String} method HTTP method
* @param {String} [key] Key name to use for req/res body
* @param {Object} [params] Request body
* @return {Promise}
* @private
*/
Recharge.prototype.request = function request(url, method, key, params) {
const options = assign({
timeout: this.options.timeout,
retries: 0,
method,
responseType: 'json'
}, url);
options.headers['User-Agent'] = `${pkg.name}/${pkg.version}`;
options.headers['Content-Type'] = 'application/json';
if (this.options.apiKey) {
options.headers['X-Recharge-Access-Token'] = this.options.apiKey;
}
if (typeof params != 'undefined') {
options.json = params;
}
return got(options).then(res => {
const body = res.body;
this.updateLimits(res.headers['x-recharge-limit']);
if (res.statusCode === 202) {
const retryAfter = res.headers['retry-after'] * 1000 || 0;
const path = urlLib.parse(res.headers['location']).path;
const newUrl = assign({ path }, this.baseUrl);
return delay(retryAfter)
.then(() => this.request(newUrl, 'GET', key));
}
if (key && body.hasOwnProperty(key)) return body[key];
return body || {};
}, err => {
this.updateLimits(
err.response && err.response.headers['x-recharge-limit']
);
return Promise.reject(err);
});
};
resources.registerAll(Recharge);
/**
* Returns a promise that resolves after a given amount of time.
*
* @param {Number} ms Amount of milliseconds to wait
* @return {Promise} Promise that resolves after `ms` milliseconds
* @private
*/
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
module.exports = Recharge;