@iamnnort/request 1.12.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,562 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/builder.ts
2
- var _qs = require('qs');
3
-
4
- // src/types.ts
5
- var HttpMethods = /* @__PURE__ */ ((HttpMethods2) => {
6
- HttpMethods2["GET"] = "get";
7
- HttpMethods2["POST"] = "post";
8
- HttpMethods2["PUT"] = "put";
9
- HttpMethods2["PATCH"] = "patch";
10
- HttpMethods2["DELETE"] = "delete";
11
- return HttpMethods2;
12
- })(HttpMethods || {});
13
- var HttpStatuses = /* @__PURE__ */ ((HttpStatuses2) => {
14
- HttpStatuses2[HttpStatuses2["CONTINUE"] = 100] = "CONTINUE";
15
- HttpStatuses2[HttpStatuses2["SWITCHING_PROTOCOLS"] = 101] = "SWITCHING_PROTOCOLS";
16
- HttpStatuses2[HttpStatuses2["PROCESSING"] = 102] = "PROCESSING";
17
- HttpStatuses2[HttpStatuses2["EARLYHINTS"] = 103] = "EARLYHINTS";
18
- HttpStatuses2[HttpStatuses2["OK"] = 200] = "OK";
19
- HttpStatuses2[HttpStatuses2["CREATED"] = 201] = "CREATED";
20
- HttpStatuses2[HttpStatuses2["ACCEPTED"] = 202] = "ACCEPTED";
21
- HttpStatuses2[HttpStatuses2["NON_AUTHORITATIVE_INFORMATION"] = 203] = "NON_AUTHORITATIVE_INFORMATION";
22
- HttpStatuses2[HttpStatuses2["NO_CONTENT"] = 204] = "NO_CONTENT";
23
- HttpStatuses2[HttpStatuses2["RESET_CONTENT"] = 205] = "RESET_CONTENT";
24
- HttpStatuses2[HttpStatuses2["PARTIAL_CONTENT"] = 206] = "PARTIAL_CONTENT";
25
- HttpStatuses2[HttpStatuses2["AMBIGUOUS"] = 300] = "AMBIGUOUS";
26
- HttpStatuses2[HttpStatuses2["MOVED_PERMANENTLY"] = 301] = "MOVED_PERMANENTLY";
27
- HttpStatuses2[HttpStatuses2["FOUND"] = 302] = "FOUND";
28
- HttpStatuses2[HttpStatuses2["SEE_OTHER"] = 303] = "SEE_OTHER";
29
- HttpStatuses2[HttpStatuses2["NOT_MODIFIED"] = 304] = "NOT_MODIFIED";
30
- HttpStatuses2[HttpStatuses2["TEMPORARY_REDIRECT"] = 307] = "TEMPORARY_REDIRECT";
31
- HttpStatuses2[HttpStatuses2["PERMANENT_REDIRECT"] = 308] = "PERMANENT_REDIRECT";
32
- HttpStatuses2[HttpStatuses2["BAD_REQUEST"] = 400] = "BAD_REQUEST";
33
- HttpStatuses2[HttpStatuses2["UNAUTHORIZED"] = 401] = "UNAUTHORIZED";
34
- HttpStatuses2[HttpStatuses2["PAYMENT_REQUIRED"] = 402] = "PAYMENT_REQUIRED";
35
- HttpStatuses2[HttpStatuses2["FORBIDDEN"] = 403] = "FORBIDDEN";
36
- HttpStatuses2[HttpStatuses2["NOT_FOUND"] = 404] = "NOT_FOUND";
37
- HttpStatuses2[HttpStatuses2["METHOD_NOT_ALLOWED"] = 405] = "METHOD_NOT_ALLOWED";
38
- HttpStatuses2[HttpStatuses2["NOT_ACCEPTABLE"] = 406] = "NOT_ACCEPTABLE";
39
- HttpStatuses2[HttpStatuses2["PROXY_AUTHENTICATION_REQUIRED"] = 407] = "PROXY_AUTHENTICATION_REQUIRED";
40
- HttpStatuses2[HttpStatuses2["REQUEST_TIMEOUT"] = 408] = "REQUEST_TIMEOUT";
41
- HttpStatuses2[HttpStatuses2["CONFLICT"] = 409] = "CONFLICT";
42
- HttpStatuses2[HttpStatuses2["GONE"] = 410] = "GONE";
43
- HttpStatuses2[HttpStatuses2["LENGTH_REQUIRED"] = 411] = "LENGTH_REQUIRED";
44
- HttpStatuses2[HttpStatuses2["PRECONDITION_FAILED"] = 412] = "PRECONDITION_FAILED";
45
- HttpStatuses2[HttpStatuses2["PAYLOAD_TOO_LARGE"] = 413] = "PAYLOAD_TOO_LARGE";
46
- HttpStatuses2[HttpStatuses2["URI_TOO_LONG"] = 414] = "URI_TOO_LONG";
47
- HttpStatuses2[HttpStatuses2["UNSUPPORTED_MEDIA_TYPE"] = 415] = "UNSUPPORTED_MEDIA_TYPE";
48
- HttpStatuses2[HttpStatuses2["REQUESTED_RANGE_NOT_SATISFIABLE"] = 416] = "REQUESTED_RANGE_NOT_SATISFIABLE";
49
- HttpStatuses2[HttpStatuses2["EXPECTATION_FAILED"] = 417] = "EXPECTATION_FAILED";
50
- HttpStatuses2[HttpStatuses2["I_AM_A_TEAPOT"] = 418] = "I_AM_A_TEAPOT";
51
- HttpStatuses2[HttpStatuses2["MISDIRECTED"] = 421] = "MISDIRECTED";
52
- HttpStatuses2[HttpStatuses2["UNPROCESSABLE_ENTITY"] = 422] = "UNPROCESSABLE_ENTITY";
53
- HttpStatuses2[HttpStatuses2["FAILED_DEPENDENCY"] = 424] = "FAILED_DEPENDENCY";
54
- HttpStatuses2[HttpStatuses2["PRECONDITION_REQUIRED"] = 428] = "PRECONDITION_REQUIRED";
55
- HttpStatuses2[HttpStatuses2["TOO_MANY_REQUESTS"] = 429] = "TOO_MANY_REQUESTS";
56
- HttpStatuses2[HttpStatuses2["INTERNAL_SERVER_ERROR"] = 500] = "INTERNAL_SERVER_ERROR";
57
- HttpStatuses2[HttpStatuses2["NOT_IMPLEMENTED"] = 501] = "NOT_IMPLEMENTED";
58
- HttpStatuses2[HttpStatuses2["BAD_GATEWAY"] = 502] = "BAD_GATEWAY";
59
- HttpStatuses2[HttpStatuses2["SERVICE_UNAVAILABLE"] = 503] = "SERVICE_UNAVAILABLE";
60
- HttpStatuses2[HttpStatuses2["GATEWAY_TIMEOUT"] = 504] = "GATEWAY_TIMEOUT";
61
- HttpStatuses2[HttpStatuses2["HTTP_VERSION_NOT_SUPPORTED"] = 505] = "HTTP_VERSION_NOT_SUPPORTED";
62
- return HttpStatuses2;
63
- })(HttpStatuses || {});
64
-
65
- // src/builder.ts
66
- var RequestBuilder = class {
67
-
68
-
69
-
70
- constructor(params) {
71
- this.baseConfig = params.baseConfig;
72
- this.requestConfig = params.requestConfig;
73
- this.config = {
74
- timeout: params.requestConfig.timeout || params.baseConfig.timeout,
75
- responseType: params.requestConfig.responseType || params.baseConfig.responseType,
76
- headers: {
77
- Accept: "application/json",
78
- "Content-Type": "application/json",
79
- ...params.baseConfig.headers,
80
- ...params.requestConfig.headers
81
- }
82
- };
83
- }
84
- makeContentType() {
85
- if (this.requestConfig.multipart) {
86
- this.config = {
87
- ...this.config,
88
- headers: {
89
- ...this.config.headers,
90
- "Content-Type": "multipart/form-data"
91
- }
92
- };
93
- return this;
94
- }
95
- if (this.requestConfig.urlencoded) {
96
- this.config = {
97
- ...this.config,
98
- headers: {
99
- ...this.config.headers,
100
- "Content-Type": "application/x-www-form-urlencoded"
101
- }
102
- };
103
- return this;
104
- }
105
- if (this.requestConfig.xml) {
106
- this.config = {
107
- ...this.config,
108
- headers: {
109
- ...this.config.headers,
110
- "Content-Type": "text/xml"
111
- }
112
- };
113
- return this;
114
- }
115
- return this;
116
- }
117
- makeAuth() {
118
- const auth = this.requestConfig.auth || this.baseConfig.auth;
119
- if (auth) {
120
- this.config = {
121
- ...this.config,
122
- auth
123
- };
124
- return this;
125
- }
126
- const bearerToken = this.requestConfig.bearerToken || this.baseConfig.bearerToken;
127
- if (bearerToken) {
128
- this.config = {
129
- ...this.config,
130
- headers: {
131
- ...this.config.headers,
132
- Authorization: `Bearer ${bearerToken}`
133
- }
134
- };
135
- return this;
136
- }
137
- const apiKey = this.requestConfig.apiKey || this.baseConfig.apiKey;
138
- if (apiKey) {
139
- this.config = {
140
- ...this.config,
141
- headers: {
142
- ...this.config.headers,
143
- "x-api-key": apiKey
144
- }
145
- };
146
- return this;
147
- }
148
- return this;
149
- }
150
- makeUrl() {
151
- const baseUrlMap = this.requestConfig.baseUrlMap || this.baseConfig.baseUrlMap;
152
- const baseUrlName = this.requestConfig.baseUrlName || this.baseConfig.baseUrlName;
153
- const urlParts = [
154
- baseUrlMap && baseUrlName ? baseUrlMap[baseUrlName] : this.baseConfig.baseUrl,
155
- this.baseConfig.url,
156
- ...this.baseConfig.urlParts || [],
157
- this.requestConfig.baseUrl,
158
- this.requestConfig.url,
159
- ...this.requestConfig.urlParts || []
160
- ].map((urlPart) => _optionalChain([urlPart, 'optionalAccess', _2 => _2.toString, 'call', _3 => _3()]));
161
- const isSecureProtocol = urlParts.some((urlPart) => _optionalChain([urlPart, 'optionalAccess', _4 => _4.includes, 'call', _5 => _5("https")]));
162
- const protocol = isSecureProtocol ? "https" : "http";
163
- const actualUrlParts = urlParts.filter((urlPart) => urlPart).map((urlPart) => {
164
- return _optionalChain([urlPart, 'optionalAccess', _6 => _6.replace, 'call', _7 => _7(/^(https?:\/\/|\/)?(.*?)(\/?)$/, "$2")]);
165
- });
166
- const url = `${protocol}://${actualUrlParts.join("/")}`;
167
- this.config = {
168
- ...this.config,
169
- url
170
- };
171
- return this;
172
- }
173
- makeMethod() {
174
- this.config = {
175
- ...this.config,
176
- method: this.requestConfig.method
177
- };
178
- return this;
179
- }
180
- makeData() {
181
- if (this.requestConfig.method === "get" /* GET */) {
182
- return this;
183
- }
184
- if (this.requestConfig.urlencoded) {
185
- this.config = {
186
- ...this.config,
187
- data: _qs.stringify.call(void 0, this.requestConfig.data)
188
- };
189
- return this;
190
- }
191
- this.config = {
192
- ...this.config,
193
- data: this.requestConfig.data
194
- };
195
- return this;
196
- }
197
- makeParams() {
198
- this.config = {
199
- ...this.config,
200
- params: this.requestConfig.params
201
- };
202
- return this;
203
- }
204
- makeSerializer() {
205
- this.config = {
206
- ...this.config,
207
- paramsSerializer: (params) => {
208
- return _qs.stringify.call(void 0, params, {
209
- arrayFormat: _optionalChain([this, 'access', _8 => _8.baseConfig, 'access', _9 => _9.serializer, 'optionalAccess', _10 => _10.array]) || "brackets",
210
- skipNulls: true
211
- });
212
- }
213
- };
214
- return this;
215
- }
216
- build() {
217
- return this.config;
218
- }
219
- };
220
-
221
- // src/data-source.ts
222
- var _axios = require('axios'); var _axios2 = _interopRequireDefault(_axios);
223
-
224
- // src/logger/builder.ts
225
-
226
- var MessageBuilder = class {
227
-
228
-
229
-
230
-
231
-
232
- constructor(config) {
233
- this.printQueue = [];
234
- this.config = config;
235
- }
236
- setRequest(request) {
237
- this.request = request;
238
- return this;
239
- }
240
- setResponse(response) {
241
- this.response = response;
242
- return this;
243
- }
244
- setError(error) {
245
- this.error = error;
246
- return this;
247
- }
248
- makeType(type) {
249
- this.printQueue.push(`[${type}]`);
250
- return this;
251
- }
252
- makeUrl() {
253
- const url = _optionalChain([this, 'access', _11 => _11.request, 'optionalAccess', _12 => _12.url]) || _optionalChain([this, 'access', _13 => _13.response, 'optionalAccess', _14 => _14.config, 'optionalAccess', _15 => _15.url]) || _optionalChain([this, 'access', _16 => _16.error, 'optionalAccess', _17 => _17.response, 'optionalAccess', _18 => _18.config, 'access', _19 => _19.url]);
254
- const params = _optionalChain([this, 'access', _20 => _20.request, 'optionalAccess', _21 => _21.params]) || _optionalChain([this, 'access', _22 => _22.response, 'optionalAccess', _23 => _23.config, 'optionalAccess', _24 => _24.params]) || _optionalChain([this, 'access', _25 => _25.error, 'optionalAccess', _26 => _26.response, 'optionalAccess', _27 => _27.config, 'access', _28 => _28.params]);
255
- if (url) {
256
- if (params) {
257
- delete params["0"];
258
- this.printQueue.push(
259
- [
260
- url,
261
- _qs.stringify.call(void 0, params, {
262
- arrayFormat: _optionalChain([this, 'access', _29 => _29.config, 'access', _30 => _30.serializer, 'optionalAccess', _31 => _31.array]) || "brackets",
263
- skipNulls: true
264
- })
265
- ].filter((_) => _).join("?")
266
- );
267
- } else {
268
- this.printQueue.push(url);
269
- }
270
- }
271
- return this;
272
- }
273
- makeMethodText() {
274
- const method = _optionalChain([this, 'access', _32 => _32.request, 'optionalAccess', _33 => _33.method]) || _optionalChain([this, 'access', _34 => _34.response, 'optionalAccess', _35 => _35.config, 'optionalAccess', _36 => _36.method]) || _optionalChain([this, 'access', _37 => _37.error, 'optionalAccess', _38 => _38.response, 'optionalAccess', _39 => _39.config, 'access', _40 => _40.method]);
275
- if (method) {
276
- this.printQueue.push(method.toUpperCase());
277
- }
278
- return this;
279
- }
280
- makeRequestData() {
281
- const data = _optionalChain([this, 'access', _41 => _41.request, 'optionalAccess', _42 => _42.data]) || _optionalChain([this, 'access', _43 => _43.response, 'optionalAccess', _44 => _44.config, 'optionalAccess', _45 => _45.data]) || _optionalChain([this, 'access', _46 => _46.error, 'optionalAccess', _47 => _47.response, 'optionalAccess', _48 => _48.config, 'access', _49 => _49.data]);
282
- if (data) {
283
- if (typeof data === "string") {
284
- this.printQueue.push(data);
285
- return this;
286
- }
287
- if (Object.keys(data).length) {
288
- this.printQueue.push(JSON.stringify(data));
289
- return this;
290
- }
291
- }
292
- return this;
293
- }
294
- makeResponseDataText() {
295
- const data = _optionalChain([this, 'access', _50 => _50.response, 'optionalAccess', _51 => _51.data]) || _optionalChain([this, 'access', _52 => _52.error, 'optionalAccess', _53 => _53.response, 'optionalAccess', _54 => _54.data]);
296
- if (data) {
297
- if (typeof data === "string") {
298
- this.printQueue.push(data);
299
- return this;
300
- }
301
- if (Object.keys(data).length) {
302
- this.printQueue.push(JSON.stringify(data));
303
- return this;
304
- }
305
- }
306
- return this;
307
- }
308
- makeStatusText() {
309
- const status = _optionalChain([this, 'access', _55 => _55.response, 'optionalAccess', _56 => _56.status]) || _optionalChain([this, 'access', _57 => _57.error, 'optionalAccess', _58 => _58.response, 'optionalAccess', _59 => _59.status]);
310
- if (status) {
311
- this.printQueue.push(`${status}`);
312
- const statusText = _optionalChain([this, 'access', _60 => _60.response, 'optionalAccess', _61 => _61.statusText]) || _optionalChain([this, 'access', _62 => _62.error, 'optionalAccess', _63 => _63.response, 'optionalAccess', _64 => _64.statusText]);
313
- if (statusText) {
314
- this.printQueue.push(statusText);
315
- }
316
- }
317
- return this;
318
- }
319
- build() {
320
- return this.printQueue.join(" ");
321
- }
322
- makeMethod() {
323
- const method = _optionalChain([this, 'access', _65 => _65.request, 'optionalAccess', _66 => _66.method]) || _optionalChain([this, 'access', _67 => _67.response, 'optionalAccess', _68 => _68.config, 'optionalAccess', _69 => _69.method]) || _optionalChain([this, 'access', _70 => _70.error, 'optionalAccess', _71 => _71.response, 'optionalAccess', _72 => _72.config, 'access', _73 => _73.method]);
324
- if (!method) {
325
- return "get" /* GET */;
326
- }
327
- return method.toLowerCase();
328
- }
329
- makeResponseData() {
330
- const data = _optionalChain([this, 'access', _74 => _74.response, 'optionalAccess', _75 => _75.data]) || _optionalChain([this, 'access', _76 => _76.error, 'optionalAccess', _77 => _77.response, 'optionalAccess', _78 => _78.data]);
331
- if (!data) {
332
- return "";
333
- }
334
- if (typeof data === "string") {
335
- return data;
336
- }
337
- return JSON.stringify(data);
338
- }
339
- makeStatus() {
340
- const status = _optionalChain([this, 'access', _79 => _79.response, 'optionalAccess', _80 => _80.status]) || _optionalChain([this, 'access', _81 => _81.error, 'optionalAccess', _82 => _82.response, 'optionalAccess', _83 => _83.status]);
341
- if (!status) {
342
- return 500 /* INTERNAL_SERVER_ERROR */;
343
- }
344
- return status;
345
- }
346
- makeResponse() {
347
- return {
348
- success: this.error === void 0,
349
- status: this.makeStatus(),
350
- method: this.makeMethod(),
351
- data: this.makeResponseData()
352
- };
353
- }
354
- };
355
-
356
- // src/logger/service.ts
357
- var LoggerService = class {
358
-
359
- constructor(config) {
360
- this.config = config;
361
- }
362
- log(message, context) {
363
- const ctx = context || this.config.name || "";
364
- if (ctx) {
365
- return console.log(`[${ctx}] ${message}`);
366
- }
367
- return console.log(message);
368
- }
369
- logRequest(request) {
370
- const loggerMessageBuilder = new MessageBuilder(this.config);
371
- const message = loggerMessageBuilder.setRequest(request).makeType("Request").makeMethodText().makeUrl().makeRequestData().build();
372
- return this.log(message);
373
- }
374
- logResponse(response) {
375
- const loggerMessageBuilder = new MessageBuilder(this.config);
376
- const message = loggerMessageBuilder.setResponse(response).makeType("Response").makeMethodText().makeUrl().makeRequestData().makeStatusText().makeResponseDataText().build();
377
- return this.log(message);
378
- }
379
- logRequestError(error) {
380
- const loggerMessageBuilder = new MessageBuilder(this.config);
381
- const message = loggerMessageBuilder.setError(error).makeType("Error").makeMethodText().makeUrl().makeRequestData().makeStatusText().makeResponseDataText().build();
382
- return this.log(message);
383
- }
384
- makeResponse(response) {
385
- const loggerMessageBuilder = new MessageBuilder(this.config);
386
- const responseData = loggerMessageBuilder.setResponse(response).makeResponse();
387
- return responseData;
388
- }
389
- makeErrorResponse(error) {
390
- const loggerMessageBuilder = new MessageBuilder(this.config);
391
- const errorResponseData = loggerMessageBuilder.setError(error).makeResponse();
392
- return errorResponseData;
393
- }
394
- };
395
-
396
- // src/data-source.ts
397
- var RequestDataSource = class {
398
-
399
- constructor(baseRequestConfig) {
400
- this.baseRequestConfig = baseRequestConfig;
401
- }
402
- common(requestConfig, responseConfig = {}) {
403
- const loggerService = new LoggerService(this.baseRequestConfig);
404
- const requestBuilder = new RequestBuilder({
405
- baseConfig: this.baseRequestConfig,
406
- requestConfig
407
- });
408
- const request = requestBuilder.makeContentType().makeAuth().makeUrl().makeMethod().makeParams().makeData().makeSerializer().build();
409
- if (this.baseRequestConfig.logger) {
410
- loggerService.logRequest(request);
411
- }
412
- return _axios2.default.request(request).then((response) => {
413
- if (this.baseRequestConfig.logger) {
414
- loggerService.logResponse(response);
415
- }
416
- if (responseConfig.raw) {
417
- return loggerService.makeResponse(response);
418
- }
419
- return response.data;
420
- }).catch((error) => {
421
- if (this.baseRequestConfig.debug) {
422
- console.log("Error:", error);
423
- }
424
- if (this.baseRequestConfig.logger) {
425
- loggerService.logRequestError(error);
426
- }
427
- if (responseConfig.raw) {
428
- return loggerService.makeErrorResponse(error);
429
- }
430
- throw _optionalChain([error, 'access', _84 => _84.response, 'optionalAccess', _85 => _85.data]) || error.response || new Error(error.message);
431
- });
432
- }
433
- async *bulkCommon(requestConfig, responseConfig = {}) {
434
- const { page, pageSize, bulkSize, ...searchDto } = requestConfig.params || {};
435
- const paginationDto = {
436
- page: page || 1,
437
- pageSize: pageSize || 30
438
- };
439
- const maxPage = bulkSize ? paginationDto.page - 1 + bulkSize : null;
440
- let pagination = {
441
- total: 0,
442
- currentPage: 0,
443
- lastPage: 0,
444
- from: 0,
445
- to: 0,
446
- pageSize: 0
447
- };
448
- do {
449
- const response = await this.common({
450
- ...requestConfig,
451
- params: {
452
- ...paginationDto,
453
- ...searchDto
454
- }
455
- });
456
- pagination = response.pagination;
457
- if (!_optionalChain([response, 'access', _86 => _86.data, 'optionalAccess', _87 => _87.length])) {
458
- return;
459
- }
460
- if (responseConfig.raw) {
461
- yield response;
462
- } else {
463
- yield response.data;
464
- }
465
- paginationDto.page += 1;
466
- } while (pagination.currentPage !== pagination.lastPage && pagination.currentPage !== maxPage);
467
- if (pagination.currentPage !== pagination.lastPage) {
468
- if (responseConfig.bulkCallback) {
469
- await responseConfig.bulkCallback(paginationDto.page);
470
- }
471
- }
472
- }
473
- search(config = {}) {
474
- return this.common({
475
- ...config,
476
- method: "get" /* GET */
477
- });
478
- }
479
- bulkSearch(config = {}) {
480
- return this.bulkCommon({
481
- ...config,
482
- method: "get" /* GET */
483
- });
484
- }
485
- async searchOne(config = {}) {
486
- const response = await this.common({
487
- ...config,
488
- method: "get" /* GET */,
489
- params: {
490
- ...config.params,
491
- pageSize: 1,
492
- extended: true,
493
- strict: true
494
- }
495
- });
496
- return _optionalChain([response, 'access', _88 => _88.data, 'optionalAccess', _89 => _89[0]]);
497
- }
498
- get(id, config = {}) {
499
- return this.common({
500
- ...config,
501
- method: "get" /* GET */,
502
- url: id
503
- });
504
- }
505
- create(config) {
506
- return this.common({
507
- ...config,
508
- method: "post" /* POST */
509
- });
510
- }
511
- bulkCreate(config) {
512
- return this.common({
513
- ...config,
514
- method: "post" /* POST */,
515
- url: "/bulk",
516
- data: {
517
- bulk: config.data
518
- }
519
- });
520
- }
521
- update(id, config) {
522
- return this.common({
523
- ...config,
524
- method: "put" /* PUT */,
525
- url: id
526
- });
527
- }
528
- bulkUpdate(config) {
529
- return this.common({
530
- ...config,
531
- method: "put" /* PUT */,
532
- url: "/bulk",
533
- data: {
534
- bulk: config.data
535
- }
536
- });
537
- }
538
- remove(id, config = {}) {
539
- return this.common({
540
- ...config,
541
- method: "delete" /* DELETE */,
542
- url: id
543
- });
544
- }
545
- };
546
-
547
- // src/helper.ts
548
- var RequestHelper = class {
549
- static sleep(seconds) {
550
- return new Promise((resolve) => {
551
- setTimeout(resolve, seconds * 1e3);
552
- });
553
- }
554
- };
555
-
556
-
557
-
558
-
559
-
560
-
561
- exports.HttpMethods = HttpMethods; exports.HttpStatuses = HttpStatuses; exports.RequestBuilder = RequestBuilder; exports.RequestDataSource = RequestDataSource; exports.RequestHelper = RequestHelper;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var d=Object.defineProperty;var a=(e,r)=>d(e,"name",{value:r,configurable:!0});var _axios = require('axios'); var _axios2 = _interopRequireDefault(_axios);var _qs = require('qs');var n=(function(e){return e.GET="get",e.POST="post",e.PUT="put",e.PATCH="patch",e.DELETE="delete",e})({}),u= exports.HttpStatuses =(function(e){return e[e.CONTINUE=100]="CONTINUE",e[e.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",e[e.PROCESSING=102]="PROCESSING",e[e.EARLYHINTS=103]="EARLYHINTS",e[e.OK=200]="OK",e[e.CREATED=201]="CREATED",e[e.ACCEPTED=202]="ACCEPTED",e[e.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",e[e.NO_CONTENT=204]="NO_CONTENT",e[e.RESET_CONTENT=205]="RESET_CONTENT",e[e.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",e[e.AMBIGUOUS=300]="AMBIGUOUS",e[e.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",e[e.FOUND=302]="FOUND",e[e.SEE_OTHER=303]="SEE_OTHER",e[e.NOT_MODIFIED=304]="NOT_MODIFIED",e[e.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",e[e.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",e[e.BAD_REQUEST=400]="BAD_REQUEST",e[e.UNAUTHORIZED=401]="UNAUTHORIZED",e[e.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",e[e.FORBIDDEN=403]="FORBIDDEN",e[e.NOT_FOUND=404]="NOT_FOUND",e[e.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",e[e.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",e[e.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",e[e.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",e[e.CONFLICT=409]="CONFLICT",e[e.GONE=410]="GONE",e[e.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",e[e.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",e[e.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",e[e.URI_TOO_LONG=414]="URI_TOO_LONG",e[e.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",e[e.REQUESTED_RANGE_NOT_SATISFIABLE=416]="REQUESTED_RANGE_NOT_SATISFIABLE",e[e.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",e[e.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",e[e.MISDIRECTED=421]="MISDIRECTED",e[e.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",e[e.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",e[e.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",e[e.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",e[e.BAD_GATEWAY=502]="BAD_GATEWAY",e[e.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",e[e.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",e[e.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",e})({});var l=class{static{a(this,"RequestBuilder")}constructor(r){this.baseConfig=r.baseConfig,this.requestConfig=r.requestConfig,this.config={timeout:r.requestConfig.timeout||r.baseConfig.timeout,responseType:r.requestConfig.responseType||r.baseConfig.responseType,headers:{Accept:"application/json","Content-Type":"application/json",...r.baseConfig.headers,...r.requestConfig.headers}}}makeContentType(){return this.requestConfig.multipart?(this.config={...this.config,headers:{...this.config.headers,"Content-Type":"multipart/form-data"}},this):this.requestConfig.urlencoded?(this.config={...this.config,headers:{...this.config.headers,"Content-Type":"application/x-www-form-urlencoded"}},this):this.requestConfig.xml?(this.config={...this.config,headers:{...this.config.headers,"Content-Type":"text/xml"}},this):this}makeAuth(){let r=this.requestConfig.auth||this.baseConfig.auth;if(r)return this.config={...this.config,auth:r},this;let i=this.requestConfig.bearerToken||this.baseConfig.bearerToken;if(i)return this.config={...this.config,headers:{...this.config.headers,Authorization:`Bearer ${i}`}},this;let o=this.requestConfig.apiKey||this.baseConfig.apiKey;return o?(this.config={...this.config,headers:{...this.config.headers,"x-api-key":o}},this):this}makeUrl(){let r=this.requestConfig.baseUrlMap||this.baseConfig.baseUrlMap,i=this.requestConfig.baseUrlName||this.baseConfig.baseUrlName,o=[r&&i?r[i]:this.baseConfig.baseUrl,this.baseConfig.url,...this.baseConfig.urlParts||[],this.requestConfig.baseUrl,this.requestConfig.url,...this.requestConfig.urlParts||[]].map(t=>_optionalChain([t, 'optionalAccess', _2 => _2.toString, 'call', _3 => _3()])),T=o.some(t=>_optionalChain([t, 'optionalAccess', _4 => _4.includes, 'call', _5 => _5("https")]))?"https":"http",s=o.filter(t=>t).map(t=>_optionalChain([t, 'optionalAccess', _6 => _6.replace, 'call', _7 => _7(/^(https?:\/\/|\/)?(.*?)(\/?)$/,"$2")])),g=`${T}://${s.join("/")}`;return this.config={...this.config,url:g},this}makeMethod(){return this.config={...this.config,method:this.requestConfig.method},this}makeData(){return this.requestConfig.method===n.GET?this:this.requestConfig.urlencoded?(this.config={...this.config,data:_qs.stringify.call(void 0, this.requestConfig.data)},this):(this.config={...this.config,data:this.requestConfig.data},this)}makeParams(){return this.config={...this.config,params:this.requestConfig.params},this}makeSerializer(){return this.config={...this.config,paramsSerializer:a(r=>_qs.stringify.call(void 0, r,{arrayFormat:_optionalChain([this, 'access', _8 => _8.baseConfig, 'access', _9 => _9.serializer, 'optionalAccess', _10 => _10.array])||"brackets",skipNulls:!0}),"paramsSerializer")},this}build(){return this.config}};var _pino = require('pino'); var _pino2 = _interopRequireDefault(_pino);var E=class{static{a(this,"MessageBuilder")}constructor(r,i){this.printQueue=[],this.config=r,this.request=i.request,this.response=i.response,this.error=i.error,this.duration=i.duration}makeUrl(){let r=_optionalChain([this, 'access', _11 => _11.request, 'optionalAccess', _12 => _12.url])||_optionalChain([this, 'access', _13 => _13.response, 'optionalAccess', _14 => _14.config, 'optionalAccess', _15 => _15.url])||_optionalChain([this, 'access', _16 => _16.error, 'optionalAccess', _17 => _17.response, 'optionalAccess', _18 => _18.config, 'access', _19 => _19.url]),i=_optionalChain([this, 'access', _20 => _20.request, 'optionalAccess', _21 => _21.params])||_optionalChain([this, 'access', _22 => _22.response, 'optionalAccess', _23 => _23.config, 'optionalAccess', _24 => _24.params])||_optionalChain([this, 'access', _25 => _25.error, 'optionalAccess', _26 => _26.response, 'optionalAccess', _27 => _27.config, 'access', _28 => _28.params]);return r&&(i?(delete i[0],this.printQueue.push([r,_qs.stringify.call(void 0, i,{arrayFormat:_optionalChain([this, 'access', _29 => _29.config, 'access', _30 => _30.serializer, 'optionalAccess', _31 => _31.array])||"brackets",skipNulls:!0})].filter(o=>o).join("?"))):this.printQueue.push(r)),this}makeMethodText(){let r=_optionalChain([this, 'access', _32 => _32.request, 'optionalAccess', _33 => _33.method])||_optionalChain([this, 'access', _34 => _34.response, 'optionalAccess', _35 => _35.config, 'optionalAccess', _36 => _36.method])||_optionalChain([this, 'access', _37 => _37.error, 'optionalAccess', _38 => _38.response, 'optionalAccess', _39 => _39.config, 'access', _40 => _40.method]);return r&&this.printQueue.push(r.toUpperCase()),this}makeRequestData(){let r=_optionalChain([this, 'access', _41 => _41.request, 'optionalAccess', _42 => _42.data])||_optionalChain([this, 'access', _43 => _43.response, 'optionalAccess', _44 => _44.config, 'optionalAccess', _45 => _45.data])||_optionalChain([this, 'access', _46 => _46.error, 'optionalAccess', _47 => _47.response, 'optionalAccess', _48 => _48.config, 'access', _49 => _49.data]);if(r){if(typeof r=="string")return this.printQueue.push(r),this;if(Object.keys(r).length)return this.printQueue.push(JSON.stringify(r)),this}return this}makeResponseDataText(){let r=_optionalChain([this, 'access', _50 => _50.response, 'optionalAccess', _51 => _51.data])||_optionalChain([this, 'access', _52 => _52.error, 'optionalAccess', _53 => _53.response, 'optionalAccess', _54 => _54.data]);if(r){if(typeof r=="string")return this.printQueue.push(r),this;if(Object.keys(r).length)return this.printQueue.push(JSON.stringify(r)),this}return this}makeStatusText(){let r=_optionalChain([this, 'access', _55 => _55.response, 'optionalAccess', _56 => _56.status])||_optionalChain([this, 'access', _57 => _57.error, 'optionalAccess', _58 => _58.response, 'optionalAccess', _59 => _59.status]);if(r){this.printQueue.push(`${r}`);let i=_optionalChain([this, 'access', _60 => _60.response, 'optionalAccess', _61 => _61.statusText])||_optionalChain([this, 'access', _62 => _62.error, 'optionalAccess', _63 => _63.response, 'optionalAccess', _64 => _64.statusText]);i&&this.printQueue.push(i)}return this}makeDuration(){return this.duration&&this.printQueue.push(`(${this.duration}ms)`),this}build(){return this.printQueue.join(" ")}makeMethod(){let r=_optionalChain([this, 'access', _65 => _65.request, 'optionalAccess', _66 => _66.method])||_optionalChain([this, 'access', _67 => _67.response, 'optionalAccess', _68 => _68.config, 'optionalAccess', _69 => _69.method])||_optionalChain([this, 'access', _70 => _70.error, 'optionalAccess', _71 => _71.response, 'optionalAccess', _72 => _72.config, 'access', _73 => _73.method]);return r?r.toLowerCase():n.GET}makeResponseData(){let r=_optionalChain([this, 'access', _74 => _74.response, 'optionalAccess', _75 => _75.data])||_optionalChain([this, 'access', _76 => _76.error, 'optionalAccess', _77 => _77.response, 'optionalAccess', _78 => _78.data]);return r?typeof r=="string"?r:JSON.stringify(r):""}makeStatus(){let r=_optionalChain([this, 'access', _79 => _79.response, 'optionalAccess', _80 => _80.status])||_optionalChain([this, 'access', _81 => _81.error, 'optionalAccess', _82 => _82.response, 'optionalAccess', _83 => _83.status]);return r||u.INTERNAL_SERVER_ERROR}makeResponse(){return{success:this.error===void 0,status:this.makeStatus(),method:this.makeMethod(),data:this.makeResponseData()}}};var f=class{static{a(this,"Logger")}constructor(r){this.config=r,this.level=r.logLevel||"info",this.logger=_pino2.default.call(void 0, {name:r.name,level:this.level,transport:{target:"pino-pretty",options:{colorize:!1,ignore:"time,pid,hostname"}}})}logRequest(r){let o=new E(this.config,{request:r}).makeMethodText().makeUrl().makeRequestData().build();this.logger.debug(o)}logResponse(r,i){let o=new E(this.config,{response:r,duration:i});o.makeMethodText().makeUrl().makeRequestData().makeStatusText(),["trace","debug"].includes(this.level)&&o.makeResponseDataText();let h=o.makeDuration().build();this.logger.info(h)}logError(r,i){let o=new E(this.config,{error:r,duration:i});o.makeMethodText().makeUrl().makeRequestData().makeStatusText(),["trace","debug"].includes(this.level)&&o.makeResponseDataText();let h=o.makeDuration().build();this.logger.error(h)}makeResponse(r){return new E(this.config,{response:r}).makeResponse()}makeErrorResponse(r){return new E(this.config,{error:r}).makeResponse()}};var R=class{static{a(this,"RequestDataSource")}constructor(r){this.config=r,this.logger=new f(r)}common(r,i={}){let h=new l({baseConfig:this.config,requestConfig:r}).makeContentType().makeAuth().makeUrl().makeMethod().makeParams().makeData().makeSerializer().build();this.logger.logRequest(h);let T=Date.now();return _axios2.default.request(h).then(s=>(this.logger.logResponse(s,Date.now()-T),i.raw?this.logger.makeResponse(s):s.data)).catch(s=>{if(this.logger.logError(s,Date.now()-T),i.raw)return this.logger.makeErrorResponse(s);throw _optionalChain([s, 'access', _84 => _84.response, 'optionalAccess', _85 => _85.data])||s.response||new Error(s.message)})}async*bulkCommon(r,i={}){let{page:o,pageSize:h,bulkSize:T,...s}=r.params||{},g={page:o||1,pageSize:h||30},t=T?g.page-1+T:null,m={total:0,currentPage:0,lastPage:0,from:0,to:0,pageSize:0};do{let c=await this.common({...r,params:{...g,...s}});if(m=c.pagination,!_optionalChain([c, 'access', _86 => _86.data, 'optionalAccess', _87 => _87.length]))return;i.raw?yield c:yield c.data,g.page+=1}while(m.currentPage!==m.lastPage&&m.currentPage!==t);m.currentPage!==m.lastPage&&i.bulkCallback&&await i.bulkCallback(g.page)}search(r={}){return this.common({...r,method:n.GET})}bulkSearch(r={}){return this.bulkCommon({...r,method:n.GET})}async searchOne(r={}){return((await this.common({...r,method:n.GET,params:{pageSize:1,extended:!0,strict:!0,...r.params}})).data||[])[0]}get(r,i={}){return this.common({...i,method:n.GET,url:r})}create(r){return this.common({...r,method:n.POST})}bulkCreate(r){return this.common({...r,method:n.POST,url:"/bulk",data:{bulk:r.data}})}update(r,i){return this.common({...i,method:n.PUT,url:r})}bulkUpdate(r){return this.common({...r,method:n.PUT,url:"/bulk",data:{bulk:r.data}})}remove(r,i={}){return this.common({...i,method:n.DELETE,url:r})}};var N=class{static{a(this,"RequestHelper")}static sleep(r){return new Promise(i=>{setTimeout(i,r*1e3)})}};exports.HttpMethods = n; exports.HttpStatuses = u; exports.RequestDataSource = R; exports.RequestHelper = N;
562
2
  //# sourceMappingURL=index.js.map