bkper-js 1.1.0 → 1.2.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/lib/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Bkper REST API Node client.
2
+ * Bkper REST API Javascript client for Node.js and browsers.
3
3
  *
4
4
  * Learn more at https://bkper.com/docs
5
5
  *
@@ -849,6 +849,17 @@ export declare interface Config {
849
849
  * Custom request error handler
850
850
  */
851
851
  requestErrorHandler?: (error: any) => any;
852
+ /**
853
+ * Custom request retry handler.
854
+ *
855
+ * This function is called when a request fails and needs to be retried.
856
+ * It provides the HTTP status code, error message, and the number of retry attempts made so far.
857
+ *
858
+ * @param code - The HTTP status code of the failed request.
859
+ * @param message - The error message associated with the failed request.
860
+ * @param attempt - The number of retry attempts made so far.
861
+ */
862
+ requestRetryHandler?: (status?: number, message?: string, attempt?: number) => Promise<void>;
852
863
  /**
853
864
  * Sets the base api url. Default to https://app.bkper.com/_ah/api/bkper
854
865
  */
package/lib/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Bkper REST API Node client.
2
+ * Bkper REST API Javascript client for Node.js and browsers.
3
3
  *
4
4
  * Learn more at https://bkper.com/docs
5
5
  *
@@ -7,111 +7,65 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
7
7
  step((generator = generator.apply(thisArg, _arguments || [])).next());
8
8
  });
9
9
  };
10
- import { request } from 'gaxios';
11
- import https from 'https';
12
- import { NODE_ENV_DEV } from '../utils.js';
13
- const httpsAgent = https && https.Agent ? new https.Agent({ keepAlive: true }) : undefined;
14
- export class HttpApiRequest {
10
+ import { HttpRequest } from './http-request.js';
11
+ export class HttpApiRequest extends HttpRequest {
15
12
  constructor(path) {
16
- this.params = [];
17
- this.headers = {};
18
- this.method = 'GET';
19
- this.payload = null;
20
- this.url = `${HttpApiRequest.config.apiBaseUrl || "https://app.bkper.com/_ah/api/bkper"}/${path}`;
21
- }
22
- setMethod(method) {
23
- this.method = method;
24
- return this;
25
- }
26
- setHeader(name, value) {
27
- if (value) {
28
- this.headers[name] = value;
29
- }
30
- return this;
31
- }
32
- addParam(name, value) {
33
- if (value) {
34
- this.params.push({ name, value });
35
- }
36
- return this;
37
- }
38
- setPayload(payload) {
39
- this.payload = typeof payload === "string" ? payload : JSON.stringify(payload);
40
- return this;
41
- }
42
- /**
43
- * Gets the result url, with query params appended.
44
- */
45
- getUrl() {
46
- let url = this.url;
47
- if (this.params != null) {
48
- let i = 0;
49
- if (url.indexOf('?') < 0) {
50
- url += '?';
51
- }
52
- else {
53
- i++;
54
- }
55
- for (const param of this.params) {
56
- if (i > 0) {
57
- url += "&";
58
- }
59
- var key = param.name;
60
- var value = param.value;
61
- if (value != null) {
62
- url += key + "=" + encodeURIComponent(value);
63
- i++;
64
- }
65
- }
66
- }
67
- return url;
13
+ super(`${HttpApiRequest.config.apiBaseUrl || "https://app.bkper.com/_ah/api/bkper"}/${path}`);
14
+ this.retry = 0;
68
15
  }
69
16
  fetch() {
17
+ const _super = Object.create(null, {
18
+ execute: { get: () => super.execute }
19
+ });
70
20
  return __awaiter(this, void 0, void 0, function* () {
71
- var _a;
72
21
  this.addCustomHeaders();
73
- this.headers['Authorization'] = `Bearer ${yield getAccessToken()}`;
22
+ this.setHeader('Authorization', `Bearer ${yield getAccessToken()}`);
74
23
  this.addParam('key', yield getApiKey());
75
24
  // this.httpRequest.setMuteHttpExceptions(true);
76
- const url = this.getUrl();
77
25
  try {
78
- return yield request({
79
- url: url,
80
- method: this.method,
81
- headers: this.headers,
82
- body: this.payload,
83
- agent: url.startsWith('https') ? httpsAgent : undefined,
84
- retryConfig: {
85
- httpMethodsToRetry: ['GET', 'PUT', 'POST', 'PATCH', 'HEAD', 'OPTIONS', 'DELETE'],
86
- statusCodesToRetry: [[100, 199], [429, 429], [500, 599]],
87
- retry: process.env.NODE_ENV == NODE_ENV_DEV ? 0 : 3,
88
- onRetryAttempt: (err) => { console.log(`${err.message} - Retrying... `); }
89
- }
90
- });
91
- }
92
- catch (e) {
93
- const customError = HttpApiRequest.config.requestErrorHandler ? HttpApiRequest.config.requestErrorHandler(e) : undefined;
94
- if (customError) {
95
- throw customError;
26
+ let resp = yield _super.execute.call(this);
27
+ if (resp.status >= 200 && resp.status < 300) {
28
+ return resp;
96
29
  }
97
- else {
98
- //Default error handler
99
- let error = (_a = e.response.data) === null || _a === void 0 ? void 0 : _a.error;
100
- if (error) {
101
- if (error.code == 404) {
102
- return { data: null };
103
- }
104
- else {
105
- throw error.message;
106
- }
30
+ else if (resp.status == 404) {
31
+ return { data: null };
32
+ }
33
+ else if (this.retry <= 3) {
34
+ this.retry++;
35
+ if (HttpApiRequest.config.requestRetryHandler) {
36
+ yield HttpApiRequest.config.requestRetryHandler(resp.status, resp.data, this.retry);
107
37
  }
108
38
  else {
109
- throw e.message;
39
+ console.log(`${resp.data} - Retrying... `);
110
40
  }
41
+ return yield this.fetch();
111
42
  }
43
+ else {
44
+ throw this.handleError(resp.data);
45
+ }
46
+ }
47
+ catch (err) {
48
+ throw this.handleError(err.toJSON ? err.toJSON() : err);
112
49
  }
113
50
  });
114
51
  }
52
+ handleError(err) {
53
+ var _a, _b;
54
+ const customError = HttpApiRequest.config.requestErrorHandler ? HttpApiRequest.config.requestErrorHandler(err) : undefined;
55
+ if (customError) {
56
+ return customError;
57
+ }
58
+ else {
59
+ //Default error handler
60
+ let error = (_b = (_a = err.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.error;
61
+ if (error) {
62
+ return error.message;
63
+ }
64
+ else {
65
+ return err.message || err;
66
+ }
67
+ }
68
+ }
115
69
  addCustomHeaders() {
116
70
  return __awaiter(this, void 0, void 0, function* () {
117
71
  if (HttpApiRequest.config.requestHeadersProvider) {
@@ -0,0 +1,78 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import https from 'https';
11
+ import axios from 'axios';
12
+ const httpsAgent = https && https.Agent ? new https.Agent({ keepAlive: true }) : undefined;
13
+ export class HttpRequest {
14
+ constructor(url) {
15
+ this.params = [];
16
+ this.headers = {};
17
+ this.method = 'GET';
18
+ this.payload = null;
19
+ this.url = url;
20
+ }
21
+ setMethod(method) {
22
+ this.method = method;
23
+ return this;
24
+ }
25
+ setHeader(name, value) {
26
+ this.headers[name] = value;
27
+ return this;
28
+ }
29
+ addParam(name, value) {
30
+ this.params.push({ name, value });
31
+ return this;
32
+ }
33
+ setPayload(payload) {
34
+ this.payload = payload;
35
+ return this;
36
+ }
37
+ /**
38
+ * Gets the result url, with query params appended.
39
+ */
40
+ getUrl() {
41
+ let url = this.url;
42
+ if (this.params != null) {
43
+ let i = 0;
44
+ if (url.indexOf('?') < 0) {
45
+ url += '?';
46
+ }
47
+ else {
48
+ i++;
49
+ }
50
+ for (const param of this.params) {
51
+ if (i > 0) {
52
+ url += "&";
53
+ }
54
+ var key = param.name;
55
+ var value = param.value;
56
+ if (value != null) {
57
+ url += key + "=" + encodeURIComponent(value);
58
+ i++;
59
+ }
60
+ }
61
+ }
62
+ return url;
63
+ }
64
+ execute() {
65
+ return __awaiter(this, void 0, void 0, function* () {
66
+ const url = this.getUrl();
67
+ return axios.request({
68
+ url: url,
69
+ method: this.method,
70
+ headers: this.headers,
71
+ data: this.payload,
72
+ httpsAgent: url.startsWith('https') ? httpsAgent : undefined,
73
+ // withCredentials: true
74
+ });
75
+ });
76
+ }
77
+ }
78
+ //# sourceMappingURL=http-request.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bkper-js",
3
- "version": "1.1.0",
3
+ "version": "1.2.1",
4
4
  "description": "Javascript client for Bkper REST API",
5
5
  "main": "./lib/index.js",
6
6
  "module": "./lib/index.js",
@@ -35,9 +35,9 @@
35
35
  },
36
36
  "dependencies": {
37
37
  "@google-cloud/local-auth": "^3.0.1",
38
+ "axios": "^1.7.7",
38
39
  "big.js": "^6.0.3",
39
40
  "dayjs": "^1.10.3",
40
- "gaxios": "^4.3.0",
41
41
  "luxon": "^1.25.0"
42
42
  },
43
43
  "devDependencies": {