@iamnnort/request 1.12.3 → 2.0.1

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.mjs CHANGED
@@ -1,562 +1,2 @@
1
- // src/builder.ts
2
- import { stringify } from "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
- baseConfig;
68
- requestConfig;
69
- config;
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) => urlPart?.toString());
161
- const isSecureProtocol = urlParts.some((urlPart) => urlPart?.includes("https"));
162
- const protocol = isSecureProtocol ? "https" : "http";
163
- const actualUrlParts = urlParts.filter((urlPart) => urlPart).map((urlPart) => {
164
- return urlPart?.replace(/^(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: stringify(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 stringify(params, {
209
- arrayFormat: this.baseConfig.serializer?.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
- import axios from "axios";
223
-
224
- // src/logger/builder.ts
225
- import { stringify as stringify2 } from "qs";
226
- var MessageBuilder = class {
227
- printQueue;
228
- request;
229
- response;
230
- error;
231
- config;
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 = this.request?.url || this.response?.config?.url || this.error?.response?.config.url;
254
- const params = this.request?.params || this.response?.config?.params || this.error?.response?.config.params;
255
- if (url) {
256
- if (params) {
257
- delete params["0"];
258
- this.printQueue.push(
259
- [
260
- url,
261
- stringify2(params, {
262
- arrayFormat: this.config.serializer?.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 = this.request?.method || this.response?.config?.method || this.error?.response?.config.method;
275
- if (method) {
276
- this.printQueue.push(method.toUpperCase());
277
- }
278
- return this;
279
- }
280
- makeRequestData() {
281
- const data = this.request?.data || this.response?.config?.data || this.error?.response?.config.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 = this.response?.data || this.error?.response?.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 = this.response?.status || this.error?.response?.status;
310
- if (status) {
311
- this.printQueue.push(`${status}`);
312
- const statusText = this.response?.statusText || this.error?.response?.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 = this.request?.method || this.response?.config?.method || this.error?.response?.config.method;
324
- if (!method) {
325
- return "get" /* GET */;
326
- }
327
- return method.toLowerCase();
328
- }
329
- makeResponseData() {
330
- const data = this.response?.data || this.error?.response?.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 = this.response?.status || this.error?.response?.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
- config;
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
- baseRequestConfig;
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 axios.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 error.response?.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 (!response.data?.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
- pageSize: 1,
491
- extended: true,
492
- strict: true,
493
- ...config.params
494
- }
495
- });
496
- return response.data?.[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
- export {
556
- HttpMethods,
557
- HttpStatuses,
558
- RequestBuilder,
559
- RequestDataSource,
560
- RequestHelper
561
- };
1
+ var T=Object.defineProperty;var u=(s,e)=>T(s,"name",{value:e,configurable:!0});import R from"pino";import{HttpMessageBuilder as c}from"@iamnnort/config/http";import{HttpMethods as U,HttpStatuses as y}from"@iamnnort/config/http";var l=(function(s){return s.FATAL="fatal",s.ERROR="error",s.WARN="warn",s.INFO="info",s.DEBUG="debug",s.TRACE="trace",s})({});var p=class{static{u(this,"Logger")}logger;config;constructor(e={}){this.config={name:"",level:l.INFO,...e},this.logger=R({name:this.config.name,level:this.config.level,transport:{target:"pino-pretty",options:{colorize:!1,ignore:"time,pid,hostname"}}})}logRequest(e){let r=new c({request:e}).makeMethodText().makeUrlText().makeRequestDataText().build();this.logger.debug(r)}logResponse(e,t){let r=new c({response:e,duration:t});r.makeMethodText().makeUrlText().makeRequestDataText().makeStatusText(),[l.TRACE,l.DEBUG].includes(this.config.level)&&r.makeResponseDataText();let i=r.makeDurationText().build();this.logger.info(i)}logError(e,t,r){let i=new c({request:e,error:t,duration:r});i.makeMethodText().makeUrlText().makeRequestDataText().makeStatusText(),[l.TRACE,l.DEBUG].includes(this.config.level)&&i.makeResponseDataText();let a=i.makeDurationText().build();this.logger.error(a)}makeResponse(e){return new c({response:e}).makeResponse()}makeErrorResponse(e){return new c({error:e}).makeResponse()}};var C=(function(s){return s.INDICES="indices",s.BRACKETS="brackets",s.REPEAT="repeat",s.COMMA="comma",s})({});import E from"axios";import{HttpMethods as h}from"@iamnnort/config/http";import{stringify as k}from"qs";import{HttpMethods as x}from"@iamnnort/config/http";var d=class{static{u(this,"RequestBuilder")}baseRequestConfig;requestConfig;config;constructor(e){this.baseRequestConfig=e.baseRequestConfig,this.requestConfig=e.requestConfig,this.config={timeout:e.requestConfig.timeout||e.baseRequestConfig.timeout,responseType:e.requestConfig.responseType||e.baseRequestConfig.responseType,headers:{Accept:"application/json","Content-Type":"application/json",...e.baseRequestConfig.headers,...e.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 e=this.requestConfig.auth||this.baseRequestConfig.auth;if(e)return this.config={...this.config,auth:e},this;let t=this.requestConfig.bearerToken||this.baseRequestConfig.bearerToken;if(t)return this.config={...this.config,headers:{...this.config.headers,Authorization:`Bearer ${t}`}},this;let r=this.requestConfig.apiKey||this.baseRequestConfig.apiKey;return r?(this.config={...this.config,headers:{...this.config.headers,"x-api-key":r}},this):this}makeUrl(){let e=this.requestConfig.baseUrlMap||this.baseRequestConfig.baseUrlMap,t=this.requestConfig.baseUrlName||this.baseRequestConfig.baseUrlName,r=[e&&t?e[t]:this.baseRequestConfig.baseUrl,this.baseRequestConfig.url,...this.baseRequestConfig.urlParts||[],this.requestConfig.baseUrl,this.requestConfig.url,...this.requestConfig.urlParts||[]].map(n=>n?.toString()),a=r.some(n=>n?.includes("https"))?"https":"http",o=r.filter(n=>n).map(n=>n?.replace(/^(https?:\/\/|\/)?(.*?)(\/?)$/,"$2")),g=`${a}://${o.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===x.GET?this:this.requestConfig.urlencoded?(this.config={...this.config,data:k(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:{serialize:u(e=>k(e,{arrayFormat:this.baseRequestConfig.serializer?.arrayFormat||C.BRACKETS,skipNulls:!0}),"serialize")}},this}build(){return this.config}};var b=class{static{u(this,"RequestDataSource")}baseRequestConfig;logger;constructor(e){this.baseRequestConfig=e,this.logger=new p(this.baseRequestConfig.logger)}common(e,t={}){let i=new d({baseRequestConfig:this.baseRequestConfig,requestConfig:e}).makeContentType().makeAuth().makeUrl().makeMethod().makeParams().makeData().makeSerializer().build();this.logger.logRequest(i);let a=Date.now();return E.request(i).then(o=>(this.logger.logResponse(o,Date.now()-a),t.raw?this.logger.makeResponse(o):o.data)).catch(o=>{if(this.logger.logError(i,o,Date.now()-a),t.raw)return this.logger.makeErrorResponse(o);throw o.response?.data||o.response||new Error(o.message)})}async*bulkCommon(e,t={}){let{page:r,pageSize:i,bulkSize:a,...o}=e.params||{},g={page:r||1,pageSize:i||30},n=a?g.page-1+a:null,m={total:0,currentPage:0,lastPage:0,from:0,to:0,pageSize:0};do{let f=await this.common({...e,params:{...g,...o}});if(m=f.pagination,!f.data?.length)return;t.raw?yield f:yield f.data,g.page+=1}while(m.currentPage!==m.lastPage&&m.currentPage!==n);m.currentPage!==m.lastPage&&t.bulkCallback&&await t.bulkCallback(g.page)}search(e={}){return this.common({...e,method:h.GET})}bulkSearch(e={}){return this.bulkCommon({...e,method:h.GET})}async searchOne(e={}){return((await this.common({...e,method:h.GET,params:{pageSize:1,extended:!0,strict:!0,...e.params}})).data||[])[0]}get(e,t={}){return this.common({...t,method:h.GET,url:e})}create(e){return this.common({...e,method:h.POST})}bulkCreate(e){return this.common({...e,method:h.POST,url:"/bulk",data:{bulk:e.data}})}update(e,t){return this.common({...t,method:h.PUT,url:e})}bulkUpdate(e){return this.common({...e,method:h.PUT,url:"/bulk",data:{bulk:e.data}})}remove(e,t={}){return this.common({...t,method:h.DELETE,url:e})}};var q=class{static{u(this,"RequestHelper")}static sleep(e){return new Promise(t=>{setTimeout(t,e*1e3)})}};export{U as HttpMethods,y as HttpStatuses,p as Logger,l as LoggerLevels,b as RequestDataSource,q as RequestHelper,C as SerializerArrayFormats};
562
2
  //# sourceMappingURL=index.mjs.map