@docbrasil/api-systemmanager 1.1.55 → 1.1.56

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.
Files changed (2) hide show
  1. package/api/dispatch.js +73 -62
  2. package/package.json +1 -1
package/api/dispatch.js CHANGED
@@ -19,13 +19,15 @@ class Dispatch {
19
19
  withCredentials: true
20
20
  });
21
21
 
22
- // Add request interceptor for offline handling
22
+ // Add request interceptor for offline handling.
23
23
  self._client.interceptors.request.use(
24
24
  async (config) => {
25
+ // If online or no cache is provided, proceed normally.
25
26
  if (self._isOnline() || !self._cache) {
26
27
  return config;
27
28
  }
28
29
 
30
+ // We're offline and caching is enabled – try to retrieve cached data.
29
31
  const cachedData = await self._getCache(config.url, {
30
32
  method: config.method,
31
33
  data: config.data,
@@ -34,54 +36,75 @@ class Dispatch {
34
36
  });
35
37
 
36
38
  if (cachedData) {
37
- config.cached = true;
38
- config.data = cachedData;
39
- return config;
39
+ // Instead of returning the modified config (which would trigger a network call),
40
+ // return a rejected promise with a flag and a fake response.
41
+ return Promise.reject({
42
+ __fromCache: true,
43
+ response: {
44
+ data: cachedData,
45
+ status: 200,
46
+ statusText: 'OK',
47
+ headers: config.headers,
48
+ config: config,
49
+ request: {} // empty placeholder
50
+ }
51
+ });
40
52
  }
41
53
 
54
+ // No cached data found – signal an offline error.
42
55
  self.errorOffline();
43
- throw new Error('Network error: No internet connection and no cached data available');
56
+ return Promise.reject(new Error('Network error: No internet connection and no cached data available'));
44
57
  },
45
58
  error => Promise.reject(error)
46
59
  );
47
60
 
48
- // Add response interceptor to handle caching
61
+ // Add response interceptor to handle caching and to return a cached response when available.
49
62
  self._client.interceptors.response.use(
50
63
  async response => {
51
- if (response.status === 200 && self._isOnline() && self._cache && !response.cached) {
52
- await self._setCache(response.config.url, {
53
- method: response.config.method,
54
- data: response.config.data,
55
- params: response.config.params,
56
- headers: response.config.headers
57
- }, response.data);
64
+ // If online, the response is OK, caching is enabled, and this wasn’t a cached response,
65
+ // then cache the new response data.
66
+ if (response.status === 200 && self._isOnline() && self._cache && !response.config.cached) {
67
+ await self._setCache(
68
+ response.config.url,
69
+ {
70
+ method: response.config.method,
71
+ data: response.config.data,
72
+ params: response.config.params,
73
+ headers: response.config.headers
74
+ },
75
+ response.data
76
+ );
58
77
  }
59
78
  return response;
60
79
  },
61
- error => Promise.reject(error)
80
+ error => {
81
+ // If the error was generated because we had a cached response, then return that response.
82
+ if (error.__fromCache && error.response) {
83
+ return Promise.resolve(error.response);
84
+ }
85
+ return Promise.reject(error);
86
+ }
62
87
  );
63
88
  }
64
89
 
65
90
  /**
66
- * @author Augusto Pissarra <abernardo.br@gmail.com>
67
- * @description Get the return data and check for errors
68
- * @param {object} retData Response HTTP
91
+ * @description Get the return data and check for errors.
92
+ * @param {object} retData Response HTTP.
93
+ * @param {*} [def={}] Default value to return if no data is found.
69
94
  * @return {*}
70
95
  * @private
71
96
  */
72
97
  _returnData(retData, def = {}) {
73
98
  if (retData.status !== 200) {
74
- throw Boom.badRequest(_.get(retData, 'message', 'No error message reported!'))
75
- } else {
76
- return _.get(retData, 'data', def);
99
+ throw new Error(_.get(retData, 'message', 'No error message reported!'));
77
100
  }
101
+ return _.get(retData, 'data', def);
78
102
  }
79
103
 
80
104
  /**
81
- * @author Myndware <augusto.pissarra@myndware.com>
82
- * @description Set header with new session
83
- * @param {string} session Session, token JWT
84
- * @return {object} header with new session
105
+ * @description Set header with new session.
106
+ * @param {string} session Session token (JWT).
107
+ * @return {object} Header object with the new session.
85
108
  * @private
86
109
  */
87
110
  _setHeader(session) {
@@ -93,20 +116,20 @@ class Dispatch {
93
116
  }
94
117
 
95
118
  /**
96
- * @description Check if the browser/client is currently online
97
- * @return {boolean} True if online, false if offline
119
+ * @description Check if the browser/client is currently online.
120
+ * @return {boolean} True if online, false if offline.
98
121
  * @private
99
122
  */
100
123
  _isOnline() {
101
- if(this._forceCache) return false;
124
+ if (this._forceCache) return false;
102
125
  return typeof navigator !== 'undefined' && navigator.onLine;
103
126
  }
104
127
 
105
128
  /**
106
- * @description Get cached data for a specific request
107
- * @param {string} url The request URL
108
- * @param {object} options Request options including method, data, params, and headers
109
- * @return {Promise<object|null>} Cached data or null if no cache exists
129
+ * @description Get cached data for a specific request.
130
+ * @param {string} url The request URL.
131
+ * @param {object} options Request options including method, data, params, and headers.
132
+ * @return {Promise<object|null>} Cached data or null if no cache exists.
110
133
  * @private
111
134
  */
112
135
  async _getCache(url, options) {
@@ -119,10 +142,10 @@ class Dispatch {
119
142
  }
120
143
 
121
144
  /**
122
- * @description Set data in cache for a specific request
123
- * @param {string} url The request URL
124
- * @param {object} options Request options including method, data, params, and headers
125
- * @param {object} data The data to cache
145
+ * @description Set data in cache for a specific request.
146
+ * @param {string} url The request URL.
147
+ * @param {object} options Request options including method, data, params, and headers.
148
+ * @param {object} data The data to cache.
126
149
  * @return {Promise<void>}
127
150
  * @private
128
151
  */
@@ -134,28 +157,28 @@ class Dispatch {
134
157
  }
135
158
  }
136
159
 
160
+ /**
161
+ * Called when no cache is available and the client is offline.
162
+ */
137
163
  errorOffline() {
138
- this._cache.errorOffline();
164
+ if (this._cache && typeof this._cache.errorOffline === 'function') {
165
+ this._cache.errorOffline();
166
+ }
139
167
  }
140
168
 
141
169
  /**
142
- * Get the URL context
143
- * @param url {string} Full url
144
- * @param session {session} Session, token JWT
145
- * @return {Promise<object>} The full data context of the URL
170
+ * Get the URL context.
171
+ * @param {string} url Full URL.
172
+ * @param {string|null} [session=null] Session token (JWT).
173
+ * @return {Promise<object>} The full data context of the URL.
146
174
  * @public
147
175
  * @async
148
- * @example
149
- *
150
- * const API = require('@docbrasil/api-systemmanager');
151
- * const api = new API();
152
- * const retContext = await api.dispatch.getContext('http://myndware.io/login/myorg);
153
- *
154
176
  */
155
177
  async getContext(url, session = null) {
156
178
  Joi.assert(url, Joi.string().required());
157
179
 
158
- if(url.includes('?')) {
180
+ // Append the json flag to the URL.
181
+ if (url.includes('?')) {
159
182
  url = `${url}&json=true`;
160
183
  } else {
161
184
  url = `${url}?json=true`;
@@ -168,24 +191,12 @@ class Dispatch {
168
191
  }
169
192
 
170
193
  /**
171
- * @author Myndware <augusto.pissarra@myndware.com>
172
- * @description Get client Axios
173
- * @return {promise} return client axios
194
+ * @description Get the Axios client.
195
+ * @return {AxiosInstance} The Axios client.
174
196
  * @public
175
- * @async
176
- * @example
177
- *
178
- * const API = require('@docbrasil/api-systemmanager');
179
- * const api = new API();
180
- * await api.dispatch.getClient();
181
197
  */
182
198
  getClient() {
183
- try {
184
- const self = this;
185
- return self._client;
186
- } catch (ex) {
187
- return ex;
188
- }
199
+ return this._client;
189
200
  }
190
201
  }
191
202
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@docbrasil/api-systemmanager",
3
3
  "description": "Module API System Manager",
4
- "version": "1.1.55",
4
+ "version": "1.1.56",
5
5
  "scripts": {
6
6
  "htmldoc": "rm -rf docs && jsdoc api/** -d docs -t ./node_modules/better-docs",
7
7
  "doc": "rm -rf doc && mkdir doc && jsdoc2md api/**/* api/* > doc/api.md",