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