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