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 | const DEBUG_MODE = false
|
27 | const RESOURCE = 0
|
28 | const ID = 1
|
29 | const ACTION = 2
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 | const qs = require('querystring')
|
41 | const request = require('superagent')
|
42 | const _path = require('path')
|
43 | const JSONb = require('json-bigint')({ storeAsString: true })
|
44 | const version = require('./package.json').version
|
45 |
|
46 |
|
47 | require('superagent-proxy')(request)
|
48 |
|
49 | function setValueIfExist(targetObject, path, value) {
|
50 | if(value) {
|
51 | targetObject[path] = value;
|
52 | }
|
53 | }
|
54 |
|
55 |
|
56 |
|
57 |
|
58 |
|
59 |
|
60 |
|
61 |
|
62 |
|
63 |
|
64 |
|
65 | function MailjetClient (api_key, api_secret, options, perform_api_call) {
|
66 | return this.authStrategy(api_key, api_secret, options, perform_api_call)
|
67 | }
|
68 |
|
69 |
|
70 |
|
71 |
|
72 |
|
73 |
|
74 |
|
75 | MailjetClient.prototype.authStrategy = function(api_key, api_secret, options, perform_api_call) {
|
76 |
|
77 | var isTokenRequired = this.isTokenRequired(api_key, api_secret, options, perform_api_call)
|
78 | var self = this
|
79 |
|
80 |
|
81 | if (isTokenRequired) {
|
82 |
|
83 |
|
84 |
|
85 |
|
86 | return tokenAuthentication(api_key, api_secret, options)
|
87 | } else {
|
88 |
|
89 | return basicAuthentication(api_key, api_secret, options, perform_api_call)
|
90 | }
|
91 |
|
92 | |
93 |
|
94 |
|
95 |
|
96 |
|
97 |
|
98 |
|
99 | function basicAuthentication(api_key, api_secret, options, perform_api_call) {
|
100 |
|
101 | self.config = self.setConfig(options)
|
102 | self.perform_api_call = perform_api_call || false
|
103 |
|
104 | self.version = version
|
105 | if (api_key && api_secret) {
|
106 | self.connect(api_key, api_secret, options)
|
107 | }
|
108 |
|
109 | return self
|
110 | }
|
111 |
|
112 | |
113 |
|
114 |
|
115 |
|
116 |
|
117 |
|
118 | function tokenAuthentication(api_token, options, perform_api_call) {
|
119 | self.perform_api_call = perform_api_call || false
|
120 |
|
121 | self.version = version
|
122 | if (api_token) {
|
123 | self.connect(api_token, options)
|
124 | }
|
125 |
|
126 | return self
|
127 | }
|
128 | }
|
129 |
|
130 | MailjetClient.prototype.isTokenRequired = function () {
|
131 | var args = [].slice.call(arguments)
|
132 | var vals = args.filter(a => a !== undefined)
|
133 |
|
134 | if (DEBUG_MODE) {
|
135 | console.log('Defined arguments: ' + JSON.stringify(vals))
|
136 | }
|
137 |
|
138 | return (vals.length === 1 || (vals.length >= 2 && typeof vals[1] === 'object'))
|
139 | }
|
140 |
|
141 | MailjetClient.prototype.typeJson = function (body) {
|
142 | var keys = Object.keys(body)
|
143 | for (var i in keys) {
|
144 | var key = keys[i]
|
145 | body[key] = parseInt(body[key]) || body[key]
|
146 | }
|
147 | return body
|
148 | }
|
149 |
|
150 |
|
151 |
|
152 |
|
153 |
|
154 |
|
155 |
|
156 |
|
157 |
|
158 |
|
159 |
|
160 | MailjetClient.connect = function (k, s, o) {
|
161 | return new MailjetClient().connect(k, s, o)
|
162 | }
|
163 |
|
164 |
|
165 |
|
166 |
|
167 |
|
168 |
|
169 |
|
170 |
|
171 |
|
172 |
|
173 |
|
174 | MailjetClient.prototype.connect = function (apiKey, apiSecret, options) {
|
175 | return this.connectStrategy(apiKey, apiSecret, options)
|
176 | }
|
177 |
|
178 |
|
179 |
|
180 |
|
181 |
|
182 |
|
183 | MailjetClient.prototype.connectStrategy = function (apiKey, apiSecret, options) {
|
184 |
|
185 | var self = this
|
186 | var isTokenRequired = this.isTokenRequired(apiKey, apiSecret, options)
|
187 |
|
188 | if (isTokenRequired) {
|
189 | return tokenConnectStrategy(apiKey, apiSecret)
|
190 | } else {
|
191 | return basicConnectStrategy(apiKey, apiSecret, options)
|
192 | }
|
193 |
|
194 | function basicConnectStrategy(apiKey, apiSecret, options) {
|
195 | if (!apiKey) {
|
196 | throw new Error('Mailjet API_KEY is required');
|
197 | }
|
198 | if (!apiSecret) {
|
199 | throw new Error('Mailjet API_SECRET is required');
|
200 | }
|
201 |
|
202 | setOptions(options)
|
203 | self.apiKey = apiKey
|
204 | self.apiSecret = apiSecret
|
205 | return self
|
206 | }
|
207 |
|
208 | function tokenConnectStrategy(apiToken, options) {
|
209 | setOptions(options)
|
210 | if (!apiToken) {
|
211 | throw new Error('Mailjet API_TOKEN is required');
|
212 | }
|
213 |
|
214 | self.apiToken = apiToken
|
215 | return self
|
216 | }
|
217 |
|
218 | function setOptions(options) {
|
219 | self.options = options || {}
|
220 | if (self.options) {
|
221 | self.config = self.setConfig(options)
|
222 | }
|
223 | }
|
224 | }
|
225 |
|
226 | MailjetClient.prototype.setConfig = function (options) {
|
227 | const config = require('./config.json')
|
228 | if (typeof options === 'object' && options != null && options.length != 0) {
|
229 | if (options.url) config.url = options.url
|
230 | if (options.version) config.version = options.version
|
231 | if (options.perform_api_call) config.perform_api_call = options.perform_api_call
|
232 | } else if (options != null) {
|
233 | throw new Error('warning, your options variable is not a valid object.')
|
234 | }
|
235 |
|
236 | return config
|
237 | }
|
238 |
|
239 |
|
240 |
|
241 |
|
242 |
|
243 |
|
244 |
|
245 |
|
246 |
|
247 |
|
248 |
|
249 |
|
250 | MailjetClient.prototype.path = function (resource, sub, params, options) {
|
251 | if (DEBUG_MODE) {
|
252 | console.log('resource =', resource)
|
253 | console.log('subPath =', sub)
|
254 | console.log('filters =', params)
|
255 | }
|
256 |
|
257 | const url = (options && 'url' in options) ? options.url : this.config.url
|
258 | const api_version = (options && 'version' in options) ? options.version : this.config.version
|
259 |
|
260 | const base = _path.join(api_version, sub)
|
261 | if (Object.keys(params).length === 0) {
|
262 | return _path.join(url, base + '/' + resource)
|
263 | }
|
264 |
|
265 | const querystring = qs.stringify(params);
|
266 | return _path.join(url, base + '/' + resource + '?' + querystring)
|
267 | }
|
268 |
|
269 |
|
270 |
|
271 |
|
272 |
|
273 |
|
274 |
|
275 |
|
276 |
|
277 |
|
278 |
|
279 |
|
280 |
|
281 | MailjetClient.prototype.httpRequest = function (method, url, data, callback, perform_api_call){
|
282 | var req = request[method](url)
|
283 | .set('user-agent', 'mailjet-api-v3-nodejs/' + this.version)
|
284 |
|
285 | .set('Content-type', url.indexOf('text:plain') > -1
|
286 | ? 'text/plain'
|
287 | : 'application/json')
|
288 |
|
289 | if (this.apiToken) {
|
290 | req.set('Authorization', 'Bearer ' + this.apiToken)
|
291 | } else {
|
292 | req.auth(this.apiKey, this.apiSecret)
|
293 | }
|
294 |
|
295 | if (this.options.proxyUrl) {
|
296 | req = req.proxy(this.options.proxyUrl)
|
297 | }
|
298 | if (this.options.timeout) {
|
299 | req = req.timeout(this.options.timeout)
|
300 | }
|
301 |
|
302 | const payload = method === 'post' || method === 'put' ? data : {}
|
303 |
|
304 | if (DEBUG_MODE) {
|
305 | console.log('Final url: ' + url)
|
306 | console.log('body: ' + JSON.stringify(payload))
|
307 | }
|
308 |
|
309 | if (perform_api_call === false || this.perform_api_call) {
|
310 | return Promise.resolve({body: payload, url: url})
|
311 | }
|
312 |
|
313 | if (method === 'delete') { method = 'del' }
|
314 | if (method === 'post' || method === 'put') { req = req.send(data) }
|
315 |
|
316 | return new Promise(function (resolve, reject) {
|
317 |
|
318 | const ret = function (err, result) {
|
319 | return typeof callback === 'function'
|
320 | ? callback(err, result)
|
321 | : err
|
322 | ? reject(err)
|
323 | : resolve(result)
|
324 | }
|
325 |
|
326 | req.end(function (err, result) {
|
327 | var body
|
328 |
|
329 | try {
|
330 | body = JSONb.parse(result.text)
|
331 | } catch (e) {
|
332 | body = {}
|
333 | }
|
334 |
|
335 | if (err) {
|
336 | const error = new Error()
|
337 | error.ErrorMessage = body.ErrorMessage || err.message
|
338 |
|
339 | error.statusCode = err.status || null
|
340 | error.response = result || null
|
341 | error.message = `Unsuccessful: Status Code: "${error.statusCode}" Message: "${error.ErrorMessage}"`
|
342 |
|
343 | setValueIfExist(error, 'ErrorIdentifier', body.ErrorIdentifier)
|
344 | setValueIfExist(error, 'ErrorCode', body.ErrorCode)
|
345 | setValueIfExist(error, 'ErrorRelatedTo', body.ErrorRelatedTo)
|
346 |
|
347 | return ret(error)
|
348 | }
|
349 |
|
350 | return ret(null, {
|
351 | response: result,
|
352 | body: body
|
353 | })
|
354 | })
|
355 | })
|
356 | }
|
357 |
|
358 |
|
359 |
|
360 |
|
361 |
|
362 |
|
363 |
|
364 |
|
365 |
|
366 |
|
367 |
|
368 | function MailjetResource (method, func, options, context) {
|
369 | this.base = func
|
370 | this.callUrl = func
|
371 | this.options = options || context.options
|
372 |
|
373 | this.resource = func.toLowerCase()
|
374 |
|
375 | this.lastAdded = RESOURCE
|
376 | var self = context
|
377 |
|
378 | |
379 |
|
380 |
|
381 | this.subPath = (function () {
|
382 | if (func.toLowerCase() !== 'send' && func.indexOf('sms') === -1) {
|
383 | return 'REST'
|
384 | }
|
385 | return ''
|
386 | })()
|
387 |
|
388 | |
389 |
|
390 |
|
391 |
|
392 |
|
393 |
|
394 |
|
395 | var that = this
|
396 | this.result = function (params, callback) {
|
397 | params = params || {}
|
398 | if (typeof params === 'function') {
|
399 | callback = params
|
400 | params = {}
|
401 | }
|
402 |
|
403 | |
404 |
|
405 |
|
406 |
|
407 | var path = self.path(that.callUrl, that.subPath, (function () {
|
408 | if (params.filters) {
|
409 | var ret = params.filters
|
410 | delete params.filters
|
411 | return ret
|
412 | } else if (method === 'get') {
|
413 | return params
|
414 | } else {
|
415 | return {}
|
416 | }
|
417 | })(), that.options)
|
418 |
|
419 | var perform_api_call = null
|
420 | if (that.options && 'perform_api_call' in that.options) {
|
421 | perform_api_call = that.options.perform_api_call
|
422 | } else {
|
423 | perform_api_call = self.config.perform_api_call
|
424 | }
|
425 |
|
426 | that.callUrl = that.base
|
427 | self.lastAdded = RESOURCE
|
428 | return self.httpRequest(method, 'https://' + path, params, callback, perform_api_call)
|
429 | }
|
430 | }
|
431 |
|
432 |
|
433 |
|
434 |
|
435 |
|
436 |
|
437 |
|
438 |
|
439 |
|
440 |
|
441 |
|
442 | MailjetResource.prototype.id = function (value) {
|
443 | if (this.lastAdded === ID && DEBUG_MODE) {
|
444 | console.warn('[WARNING] your request may fail due to invalid id chaining')
|
445 | }
|
446 |
|
447 | this.callUrl = _path.join(this.callUrl, value.toString())
|
448 | this.lastAdded = ID
|
449 | return this
|
450 | }
|
451 |
|
452 |
|
453 |
|
454 |
|
455 |
|
456 |
|
457 |
|
458 |
|
459 |
|
460 |
|
461 |
|
462 | MailjetResource.prototype.action = function (name) {
|
463 | if (this.lastAdded === ACTION && DEBUG_MODE) {
|
464 | console.warn('[WARNING] your request may fail due to invalid action chaining')
|
465 | }
|
466 |
|
467 | this.callUrl = _path.join(this.callUrl, name)
|
468 | this.action = name.toLowerCase()
|
469 |
|
470 | this.lastAdded = ACTION
|
471 |
|
472 | if (this.action.toLowerCase() === 'csvdata') {
|
473 | this.action = 'csvdata/text:plain'
|
474 | } else if (this.action.toLowerCase() === 'csverror') {
|
475 | this.action = 'csverror/text:csv'
|
476 | }
|
477 |
|
478 | var self = this
|
479 | this.subPath = (function () {
|
480 | if (self.resource === 'contactslist' && self.action === 'csvdata/text:plain' ||
|
481 | self.resource === 'batchjob' && self.action === 'csverror/text:csv') {
|
482 | return 'DATA'
|
483 | } else {
|
484 | return self.subPath
|
485 | }
|
486 | })()
|
487 | return self
|
488 | }
|
489 |
|
490 |
|
491 |
|
492 |
|
493 |
|
494 |
|
495 |
|
496 |
|
497 |
|
498 |
|
499 |
|
500 | MailjetResource.prototype.request = function (params, callback) {
|
501 | return this.result(params, callback).catch(function (err) {
|
502 | try {
|
503 | const ErrorDetails = JSON.parse(err.response.text);
|
504 | const fullMessage = ErrorDetails.Messages[0].Errors[0].ErrorMessage;
|
505 |
|
506 | if (typeof fullMessage === "string") {
|
507 | err.message = err.message + ";\n" + fullMessage;
|
508 | throw err;
|
509 | }
|
510 | throw err;
|
511 | } catch {
|
512 | throw err;
|
513 | }
|
514 | });
|
515 | };
|
516 |
|
517 |
|
518 |
|
519 |
|
520 |
|
521 |
|
522 |
|
523 |
|
524 | MailjetClient.prototype.post = function (func, options) {
|
525 | return new MailjetResource('post', func, options, this)
|
526 | }
|
527 |
|
528 |
|
529 |
|
530 |
|
531 |
|
532 |
|
533 |
|
534 |
|
535 | MailjetClient.prototype.get = function (func, options) {
|
536 | return new MailjetResource('get', func, options, this)
|
537 | }
|
538 |
|
539 |
|
540 |
|
541 |
|
542 |
|
543 |
|
544 |
|
545 |
|
546 | MailjetClient.prototype.delete = function (func, options) {
|
547 | return new MailjetResource('delete', func, options, this)
|
548 | }
|
549 |
|
550 |
|
551 |
|
552 |
|
553 |
|
554 |
|
555 |
|
556 |
|
557 | MailjetClient.prototype.put = function (func, options) {
|
558 | return new MailjetResource('put', func, options, this)
|
559 | }
|
560 |
|
561 |
|
562 |
|
563 |
|
564 |
|
565 |
|
566 |
|
567 |
|
568 |
|
569 |
|
570 | module.exports = MailjetClient
|