UNPKG

8.16 kBJavaScriptView Raw
1'use strict';
2
3var _lodash = require('lodash.defaults');
4
5var _lodash2 = _interopRequireDefault(_lodash);
6
7var _fs = require('fs');
8
9var _fs2 = _interopRequireDefault(_fs);
10
11var _lodash3 = require('lodash.keys');
12
13var _lodash4 = _interopRequireDefault(_lodash3);
14
15var _axios = require('axios');
16
17var _axios2 = _interopRequireDefault(_axios);
18
19var _url = require('url');
20
21var _url2 = _interopRequireDefault(_url);
22
23var _https = require('https');
24
25var _https2 = _interopRequireDefault(_https);
26
27var _config = require('./config');
28
29var _config2 = _interopRequireDefault(_config);
30
31var _generateSignedParams = require('./generate-signed-params');
32
33var _generateSignedParams2 = _interopRequireDefault(_generateSignedParams);
34
35function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
36
37function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
38
39function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
40
41function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
42
43var debug = !!process.env.DEBUG;
44
45var ClientError = function (_Error) {
46 _inherits(ClientError, _Error);
47
48 function ClientError(message, statusCode) {
49 _classCallCheck(this, ClientError);
50
51 var _this = _possibleConstructorReturn(this, (ClientError.__proto__ || Object.getPrototypeOf(ClientError)).call(this, message));
52
53 _this.statusCode = statusCode;
54 return _this;
55 }
56
57 return ClientError;
58}(Error);
59
60/**
61 * @class JScramblerClient
62 * @param {Object} options
63 * @param {String} options.accessKey
64 * @param {String} options.secretKey
65 * @param {String} [options.host=api.jscrambler.com]
66 * @param {String} [options.port=443]
67 * @param {String} [options.basePath]
68 * @param {String} [options.clientId=0]
69 * @author José Magalhães (magalhas@gmail.com)
70 * @license MIT <http://opensource.org/licenses/MIT>
71 */
72
73function JScramblerClient(options) {
74 // Sluggish hack for backwards compatibility
75 if (options && !options.keys && (options.accessKey || options.secretKey)) {
76 options.keys = {};
77 options.keys.accessKey = options.accessKey;
78 options.keys.secretKey = options.secretKey;
79 }
80
81 options.keys = (0, _lodash2.default)(options.keys || {}, _config2.default.keys);
82
83 /**
84 * @member
85 */
86 this.options = (0, _lodash2.default)(options || {}, _config2.default);
87
88 var _options = this.options,
89 jscramblerVersion = _options.jscramblerVersion,
90 clientId = _options.clientId;
91
92
93 this.axiosInstance = _axios2.default.create({
94 headers: {
95 jscramblerVersion: jscramblerVersion,
96 clientId: clientId
97 },
98 maxContentLength: 100 * 1000 * 1000 // 100 MB
99 });
100}
101/**
102 * Delete request.
103 * @param {String} path
104 * @param {Object} params
105 * @param {Callback} callback
106 */
107JScramblerClient.prototype.delete = function (path, params) {
108 return this.request('DELETE', path, params);
109};
110/**
111 * Get request.
112 * @param {String} path
113 * @param {Object} params
114 * @param {Callback} callback
115 */
116JScramblerClient.prototype.get = function (path, params) {
117 var isJSON = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
118
119 return this.request('GET', path, params, isJSON);
120};
121/**
122 * HTTP request.
123 * @param {String} method
124 * @param {String} path
125 * @param {Object} params
126 * @param {Callback} callback
127 */
128JScramblerClient.prototype.request = function (method, path) {
129 var params = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
130 var isJSON = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
131
132 var signedData = void 0;
133 if (this.options.useHeaderAuth) {
134 if (!this.token) {
135 throw new Error('Generating auth token when useHeaderAuth === true is not yet supported. You need to set the jscramblerClient token property explicitly.');
136 }
137 } else {
138 if (this.token) {
139 params.token = this.token;
140 } else {
141 if (!this.options.keys.accessKey) {
142 throw new Error('Required *accessKey* not provided');
143 }
144
145 if (!this.options.keys.secretKey) {
146 throw new Error('Required *secretKey* not provided');
147 }
148 }
149 }
150
151 var _keys = (0, _lodash4.default)(params);
152 for (var i = 0, l = _keys.length; i < l; i++) {
153 if (params[_keys[i]] instanceof Array) {
154 params[_keys[i]] = params[_keys[i]].join(',');
155 }
156 }
157
158 // If post sign data and set the request as multipart
159 if (this.options.keys.accessKey && this.options.keys.secretKey) {
160 signedData = (0, _generateSignedParams2.default)(method, path, this.options.host, this.options.keys, params);
161 } else {
162 signedData = params;
163 }
164
165 var _options2 = this.options,
166 protocol = _options2.protocol,
167 port = _options2.port,
168 proxy = _options2.proxy;
169
170
171 if (!port && !protocol) {
172 port = 443;
173 protocol = 'https';
174 }
175
176 if (!port) {
177 port = protocol === 'https' ? 443 : 80;
178 }
179
180 if (!protocol) {
181 protocol = port === 443 ? 'https' : 'http';
182 }
183
184 var formatedUrl = _url2.default.format({
185 hostname: this.options.host,
186 port: port,
187 pathname: this.options.basePath + path,
188 protocol: protocol
189 });
190
191 var data = void 0;
192 var settings = {};
193
194 if (proxy) {
195 settings.proxy = proxy;
196 }
197
198 if (!isJSON) {
199 settings.responseType = 'arraybuffer';
200 }
201
202 // Internal CA
203 if (this.options.cafile) {
204 var agent = new _https2.default.Agent({
205 ca: _fs2.default.readFileSync(this.options.cafile)
206 });
207 settings.httpsAgent = agent;
208 }
209
210 var promise = void 0;
211
212 if (method === 'GET' || method === 'DELETE') {
213 settings.params = signedData;
214 promise = this.axiosInstance[method.toLowerCase()](formatedUrl, settings);
215 } else {
216 data = signedData;
217 promise = this.axiosInstance[method.toLowerCase()](formatedUrl, data, settings);
218 }
219
220 return promise.then(function (res) {
221 return res.data;
222 }).catch(function (err) {
223 var errorMessage = 'Unexpected Response: ';
224 var statusCode = 500;
225
226 if (err.response) {
227 if (debug) {
228 console.error(err.response);
229 }
230
231 errorMessage += err.response.status + ' ' + err.response.statusText;
232 statusCode = err.response.status;
233
234 // For when we have API error messages
235 if (err.response.data && err.response.data.error && err.response.data.message) {
236 errorMessage += ' - ' + err.response.data.message;
237 } else if (err.response.data && err.response.data.errors && err.response.data.errors.length > 0) {
238 errorMessage += ' - ' + err.response.data.errors;
239 }
240 } else {
241 errorMessage += err.message;
242 }
243
244 throw new ClientError(errorMessage, statusCode);
245 });
246};
247/**
248 * Post request.
249 * @param {String} path
250 * @param {Object} params
251 * @param {Callback} callback
252 */
253JScramblerClient.prototype.post = function (path, params) {
254 return this.request('POST', path, params);
255};
256/**
257 * Patch request.
258 * @param {string} path
259 * @param {object} params
260 */
261JScramblerClient.prototype.patch = function (path, params) {
262 return this.request('PATCH', path, params);
263};
264
265var _token = void 0;
266
267Object.defineProperty(JScramblerClient.prototype, 'token', {
268 get: function get() {
269 return _token;
270 },
271 set: function set(value) {
272 _token = value;
273 if (value) {
274 if (this.options.useHeaderAuth) {
275 this.axiosInstance.defaults.headers['x-user-authentication'] = _token;
276 }
277 } else {
278 delete this.axiosInstance.defaults.headers['x-user-authentication'];
279 }
280 }
281});
282
283exports = module.exports = JScramblerClient;
\No newline at end of file