-
Notifications
You must be signed in to change notification settings - Fork 47
/
ApiClient.js
601 lines (560 loc) · 21.1 KB
/
ApiClient.js
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
/*
* SendinBlue API
* SendinBlue provide a RESTFul API that can be used with any languages. With this API, you will be able to : - Manage your campaigns and get the statistics - Manage your contacts - Send transactional Emails and SMS - and much more... You can download our wrappers at https://github.com/orgs/sendinblue **Possible responses** | Code | Message | | :-------------: | ------------- | | 200 | OK. Successful Request | | 201 | OK. Successful Creation | | 202 | OK. Request accepted | | 204 | OK. Successful Update/Deletion | | 400 | Error. Bad Request | | 401 | Error. Authentication Needed | | 402 | Error. Not enough credit, plan upgrade needed | | 403 | Error. Permission denied | | 404 | Error. Object does not exist | | 405 | Error. Method not allowed | | 406 | Error. Not Acceptable |
*
* OpenAPI spec version: 3.0.0
* Contact: contact@sendinblue.com
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
*
* Swagger Codegen version: 2.4.26
*
* Do not edit the class manually.
*
*/
const pkgJson = require('../package.json');
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['superagent', 'querystring'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('superagent'), require('querystring'));
} else {
// Browser globals (root is window)
if (!root.SibApiV3Sdk) {
root.SibApiV3Sdk = {};
}
root.SibApiV3Sdk.ApiClient = factory(root.superagent, root.querystring);
}
}(this, function(superagent, querystring) {
'use strict';
/**
* @module ApiClient
* @version 8.5.0
*/
/**
* Manages low level client-server communications, parameter marshalling, etc. There should not be any need for an
* application to use this class directly - the *Api and model classes provide the public API for the service. The
* contents of this file should be regarded as internal but are documented for completeness.
* @alias module:ApiClient
* @class
*/
var exports = function() {
/**
* The base URL against which to resolve every API call's (relative) path.
* @type {String}
* @default https://api.sendinblue.com/v3
*/
this.basePath = 'https://api.sendinblue.com/v3'.replace(/\/+$/, '');
/**
* The authentication methods to be included for all API calls.
* @type {Array.<String>}
*/
this.authentications = {
'api-key': {type: 'apiKey', 'in': 'header', name: 'api-key'},
'partner-key': {type: 'apiKey', 'in': 'header', name: 'partner-key'}
};
/**
* The default HTTP headers to be included for all API calls.
* @type {Array.<String>}
* @default {}
*/
this.defaultHeaders = {
'user-agent': `sendinblue_clientAPI/v${pkgJson.version}/node`
};
/**
* The default HTTP timeout for all API calls.
* @type {Number}
* @default 60000
*/
this.timeout = 60000;
/**
* If set to false an additional timestamp parameter is added to all API GET calls to
* prevent browser caching
* @type {Boolean}
* @default true
*/
this.cache = true;
/**
* If set to true, the client will save the cookies from each server
* response, and return them in the next request.
* @default false
*/
this.enableCookies = false;
/*
* Used to save and return cookies in a node.js (non-browser) setting,
* if this.enableCookies is set to true.
*/
if (typeof window === 'undefined') {
this.agent = new superagent.agent();
}
/*
* Allow user to override superagent agent
*/
this.requestAgent = null;
};
/**
* Returns a string representation for an actual parameter.
* @param param The actual parameter.
* @returns {String} The string representation of <code>param</code>.
*/
exports.prototype.paramToString = function(param) {
if (param == undefined || param == null) {
return '';
}
if (param instanceof Date) {
return param.toISOString();
}
return param.toString();
};
/**
* Builds full URL by appending the given path to the base URL and replacing path parameter place-holders with parameter values.
* NOTE: query parameters are not handled here.
* @param {String} path The path to append to the base URL.
* @param {Object} pathParams The parameter values to append.
* @returns {String} The encoded path with parameter values substituted.
*/
exports.prototype.buildUrl = function(path, pathParams) {
if (!path.match(/^\//)) {
path = '/' + path;
}
var url = this.basePath + path;
var _this = this;
url = url.replace(/\{([\w-]+)\}/g, function(fullMatch, key) {
var value;
if (pathParams.hasOwnProperty(key)) {
value = _this.paramToString(pathParams[key]);
} else {
value = fullMatch;
}
return encodeURIComponent(value);
});
return url;
};
/**
* Checks whether the given content type represents JSON.<br>
* JSON content type examples:<br>
* <ul>
* <li>application/json</li>
* <li>application/json; charset=UTF8</li>
* <li>APPLICATION/JSON</li>
* </ul>
* @param {String} contentType The MIME content type to check.
* @returns {Boolean} <code>true</code> if <code>contentType</code> represents JSON, otherwise <code>false</code>.
*/
exports.prototype.isJsonMime = function(contentType) {
return Boolean(contentType != null && contentType.match(/^application\/json(;.*)?$/i));
};
/**
* Chooses a content type from the given array, with JSON preferred; i.e. return JSON if included, otherwise return the first.
* @param {Array.<String>} contentTypes
* @returns {String} The chosen content type, preferring JSON.
*/
exports.prototype.jsonPreferredMime = function(contentTypes) {
for (var i = 0; i < contentTypes.length; i++) {
if (this.isJsonMime(contentTypes[i])) {
return contentTypes[i];
}
}
return contentTypes[0];
};
/**
* Checks whether the given parameter value represents file-like content.
* @param param The parameter to check.
* @returns {Boolean} <code>true</code> if <code>param</code> represents a file.
*/
exports.prototype.isFileParam = function(param) {
// fs.ReadStream in Node.js and Electron (but not in runtime like browserify)
if (typeof require === 'function') {
var fs;
try {
fs = require('fs');
} catch (err) {}
if (fs && fs.ReadStream && param instanceof fs.ReadStream) {
return true;
}
}
// Buffer in Node.js
if (typeof Buffer === 'function' && param instanceof Buffer) {
return true;
}
// Blob in browser
if (typeof Blob === 'function' && param instanceof Blob) {
return true;
}
// File in browser (it seems File object is also instance of Blob, but keep this for safe)
if (typeof File === 'function' && param instanceof File) {
return true;
}
return false;
};
/**
* Normalizes parameter values:
* <ul>
* <li>remove nils</li>
* <li>keep files and arrays</li>
* <li>format to string with `paramToString` for other cases</li>
* </ul>
* @param {Object.<String, Object>} params The parameters as object properties.
* @returns {Object.<String, Object>} normalized parameters.
*/
exports.prototype.normalizeParams = function(params) {
var newParams = {};
for (var key in params) {
if (params.hasOwnProperty(key) && params[key] != undefined && params[key] != null) {
var value = params[key];
if (this.isFileParam(value) || Array.isArray(value)) {
newParams[key] = value;
} else {
newParams[key] = this.paramToString(value);
}
}
}
return newParams;
};
/**
* Enumeration of collection format separator strategies.
* @enum {String}
* @readonly
*/
exports.CollectionFormatEnum = {
/**
* Comma-separated values. Value: <code>csv</code>
* @const
*/
CSV: ',',
/**
* Space-separated values. Value: <code>ssv</code>
* @const
*/
SSV: ' ',
/**
* Tab-separated values. Value: <code>tsv</code>
* @const
*/
TSV: '\t',
/**
* Pipe(|)-separated values. Value: <code>pipes</code>
* @const
*/
PIPES: '|',
/**
* Native array. Value: <code>multi</code>
* @const
*/
MULTI: 'multi'
};
/**
* Builds a string representation of an array-type actual parameter, according to the given collection format.
* @param {Array} param An array parameter.
* @param {module:ApiClient.CollectionFormatEnum} collectionFormat The array element separator strategy.
* @returns {String|Array} A string representation of the supplied collection, using the specified delimiter. Returns
* <code>param</code> as is if <code>collectionFormat</code> is <code>multi</code>.
*/
exports.prototype.buildCollectionParam = function buildCollectionParam(param, collectionFormat) {
if (param == null) {
return null;
}
switch (collectionFormat) {
case 'csv':
return param.map(this.paramToString).join(',');
case 'ssv':
return param.map(this.paramToString).join(' ');
case 'tsv':
return param.map(this.paramToString).join('\t');
case 'pipes':
return param.map(this.paramToString).join('|');
case 'multi':
// return the array directly as SuperAgent will handle it as expected
return param.map(this.paramToString);
default:
throw new Error('Unknown collection format: ' + collectionFormat);
}
};
/**
* Applies authentication headers to the request.
* @param {Object} request The request object created by a <code>superagent()</code> call.
* @param {Array.<String>} authNames An array of authentication method names.
*/
exports.prototype.applyAuthToRequest = function(request, authNames) {
var _this = this;
authNames.forEach(function(authName) {
var auth = _this.authentications[authName];
switch (auth.type) {
case 'basic':
if (auth.username || auth.password) {
request.auth(auth.username || '', auth.password || '');
}
break;
case 'apiKey':
if (auth.apiKey) {
var data = {};
if (auth.apiKeyPrefix) {
data[auth.name] = auth.apiKeyPrefix + ' ' + auth.apiKey;
} else {
data[auth.name] = auth.apiKey;
}
if (auth['in'] === 'header') {
request.set(data);
} else {
request.query(data);
}
}
break;
case 'oauth2':
if (auth.accessToken) {
request.set({'Authorization': 'Bearer ' + auth.accessToken});
}
break;
default:
throw new Error('Unknown authentication type: ' + auth.type);
}
});
};
/**
* Deserializes an HTTP response body into a value of the specified type.
* @param {Object} response A SuperAgent response object.
* @param {(String|Array.<String>|Object.<String, Object>|Function)} returnType The type to return. Pass a string for simple types
* or the constructor function for a complex type. Pass an array containing the type name to return an array of that type. To
* return an object, pass an object with one property whose name is the key type and whose value is the corresponding value type:
* all properties on <code>data<code> will be converted to this type.
* @returns A value of the specified type.
*/
exports.prototype.deserialize = function deserialize(response, returnType) {
if (response == null || returnType == null || response.status == 204) {
return null;
}
// Rely on SuperAgent for parsing response body.
// See http://visionmedia.github.io/superagent/#parsing-response-bodies
var data = response.body;
if (data == null || (typeof data === 'object' && typeof data.length === 'undefined' && !Object.keys(data).length)) {
// SuperAgent does not always produce a body; use the unparsed response as a fallback
data = response.text;
}
return exports.convertToType(data, returnType);
};
/**
* Invokes the REST service using the supplied settings and parameters.
* @param {String} path The base URL to invoke.
* @param {String} httpMethod The HTTP method to use.
* @param {Object.<String, String>} pathParams A map of path parameters and their values.
* @param {Object.<String, Object>} queryParams A map of query parameters and their values.
* @param {Object.<String, Object>} collectionQueryParams A map of collection query parameters and their values.
* @param {Object.<String, Object>} headerParams A map of header parameters and their values.
* @param {Object.<String, Object>} formParams A map of form parameters and their values.
* @param {Object} bodyParam The value to pass as the request body.
* @param {Array.<String>} authNames An array of authentication type names.
* @param {Array.<String>} contentTypes An array of request MIME types.
* @param {Array.<String>} accepts An array of acceptable response MIME types.
* @param {(String|Array|ObjectFunction)} returnType The required type to return; can be a string for simple types or the
* constructor for a complex type.
* @returns {Promise} A {@link https://www.promisejs.org/|Promise} object.
*/
exports.prototype.callApi = function callApi(path, httpMethod, pathParams,
queryParams, collectionQueryParams, headerParams, formParams, bodyParam, authNames, contentTypes, accepts,
returnType) {
var _this = this;
var url = this.buildUrl(path, pathParams);
var request = superagent(httpMethod, url);
// apply authentications
this.applyAuthToRequest(request, authNames);
// set collection query parameters
for (var key in collectionQueryParams) {
if (collectionQueryParams.hasOwnProperty(key)) {
var param = collectionQueryParams[key];
if (param.collectionFormat === 'csv') {
// SuperAgent normally percent-encodes all reserved characters in a query parameter. However,
// commas are used as delimiters for the 'csv' collectionFormat so they must not be encoded. We
// must therefore construct and encode 'csv' collection query parameters manually.
if (param.value != null) {
var value = param.value.map(this.paramToString).map(encodeURIComponent).join(',');
request.query(encodeURIComponent(key) + "=" + value);
}
} else {
// All other collection query parameters should be treated as ordinary query parameters.
queryParams[key] = this.buildCollectionParam(param.value, param.collectionFormat);
}
}
}
// set query parameters
if (httpMethod.toUpperCase() === 'GET' && this.cache === false) {
queryParams['_'] = new Date().getTime();
}
request.query(this.normalizeParams(queryParams));
// set header parameters
request.set(this.defaultHeaders).set(this.normalizeParams(headerParams));
// set requestAgent if it is set by user
if (this.requestAgent) {
request.agent(this.requestAgent);
}
// set request timeout
request.timeout(this.timeout);
var contentType = this.jsonPreferredMime(contentTypes);
if (contentType) {
// Issue with superagent and multipart/form-data (https://github.com/visionmedia/superagent/issues/746)
if(contentType != 'multipart/form-data') {
request.type(contentType);
}
} else if (!request.header['Content-Type']) {
request.type('application/json');
}
if (contentType === 'application/x-www-form-urlencoded') {
request.send(querystring.stringify(this.normalizeParams(formParams)));
} else if (contentType == 'multipart/form-data') {
var _formParams = this.normalizeParams(formParams);
for (var key in _formParams) {
if (_formParams.hasOwnProperty(key)) {
if (this.isFileParam(_formParams[key])) {
// file field
request.attach(key, _formParams[key]);
} else {
request.field(key, _formParams[key]);
}
}
}
} else if (bodyParam) {
request.send(bodyParam);
}
var accept = this.jsonPreferredMime(accepts);
if (accept) {
request.accept(accept);
}
// if (returnType === 'Blob') {
// request.responseType('blob');
// } else if (returnType === 'String') {
// request.responseType('string');
// }
// Attach previously saved cookies, if enabled
if (this.enableCookies){
if (typeof window === 'undefined') {
this.agent.attachCookies(request);
}
else {
request.withCredentials();
}
}
return new Promise(function(resolve, reject) {
request.end(function(error, response) {
if (error) {
reject(error);
} else {
try {
var data = _this.deserialize(response, returnType);
if (_this.enableCookies && typeof window === 'undefined'){
_this.agent.saveCookies(response);
}
resolve({data: data, response: response});
} catch (err) {
reject(err);
}
}
});
});
};
/**
* Parses a string representation of a date value.
* @param {String} str The date value as an ISO-8601 full-date or date-time string.
* @returns {Date} The parsed date object.
*/
exports.parseDate = function(str) {
// OpenAPI 2.0 & 3.0 specs state that:
// - date values are serialized as ISO-8601 full-date strings.
// - date-time values are serialized as ISO-8601 date-time strings, in which the timezone offset is mandatory.
return new Date(str);
};
/**
* Converts a value to the specified type.
* @param {(String|Object)} data The data to convert, as a string or object.
* @param {(String|Array.<String>|Object.<String, Object>|Function)} type The type to return. Pass a string for simple types
* or the constructor function for a complex type. Pass an array containing the type name to return an array of that type. To
* return an object, pass an object with one property whose name is the key type and whose value is the corresponding value type:
* all properties on <code>data<code> will be converted to this type.
* @returns An instance of the specified type or null or undefined if data is null or undefined.
*/
exports.convertToType = function(data, type) {
if (data === null || data === undefined)
return data
switch (type) {
case 'Boolean':
return Boolean(data);
case 'Integer':
return parseInt(data, 10);
case 'Number':
return parseFloat(data);
case 'String':
return String(data);
case 'Date':
return this.parseDate(String(data));
case 'Blob':
return data;
default:
if (type === Object) {
// generic object, return directly
return data;
} else if (typeof type === 'function') {
// for model type like: User
return type.constructFromObject(data);
} else if (Array.isArray(type)) {
// for array type like: ['String']
var itemType = type[0];
return data.map(function(item) {
return exports.convertToType(item, itemType);
});
} else if (typeof type === 'object') {
// for plain object type like: {'String': 'Integer'}
var keyType, valueType;
for (var k in type) {
if (type.hasOwnProperty(k)) {
keyType = k;
valueType = type[k];
break;
}
}
var result = {};
for (var k in data) {
if (data.hasOwnProperty(k)) {
var key = exports.convertToType(k, keyType);
var value = exports.convertToType(data[k], valueType);
result[key] = value;
}
}
return result;
} else {
// for unknown type, return the data directly
return data;
}
}
};
/**
* Constructs a new map or array model from REST data.
* @param data {Object|Array} The REST data.
* @param obj {Object|Array} The target object or array.
*/
exports.constructFromObject = function(data, obj, itemType) {
if (Array.isArray(data)) {
for (var i = 0; i < data.length; i++) {
if (data.hasOwnProperty(i))
obj[i] = exports.convertToType(data[i], itemType);
}
} else {
for (var k in data) {
if (data.hasOwnProperty(k))
obj[k] = exports.convertToType(data[k], itemType);
}
}
};
exports.setUserAgent = function(header) {
if (typeof header == 'string' && header.substr(0,11).trim().toLowerCase() === 'sendinblue_') {
exports.instance.defaultHeaders['user-agent'] = header;
}
return;
};
/**
* The default API client implementation.
* @type {module:ApiClient}
*/
exports.instance = new exports();
return exports;
}));