@alwatr/fetch 0.25.0 → 0.26.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/CHANGELOG.md CHANGED
@@ -3,6 +3,35 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ ## [0.26.1](https://github.com/AliMD/alwatr/compare/v0.26.0...v0.26.1) (2022-12-25)
7
+
8
+ **Note:** Version bump only for package @alwatr/fetch
9
+
10
+ # [0.26.0](https://github.com/AliMD/alwatr/compare/v0.25.0...v0.26.0) (2022-12-22)
11
+
12
+ ### Bug Fixes
13
+
14
+ - all import without .js ([fa739ab](https://github.com/AliMD/alwatr/commit/fa739ab23f67bae1d10bfcc146920b71377a26fc))
15
+ - **core/fetch:** tsconfig refrences ([e6b9542](https://github.com/AliMD/alwatr/commit/e6b9542284e67b67600da4dcebd19daedb031c9c))
16
+ - **fetch:** always call revalidateCallback ([444edc5](https://github.com/AliMD/alwatr/commit/444edc52b6dd5de5418ae8630e1f2270f0114372))
17
+ - **fetch:** enhance handle and report errors in serviceRequest ([dbfc7ff](https://github.com/AliMD/alwatr/commit/dbfc7ff2a036216498dc8e2ff58b74b7eb8d9bc0))
18
+ - **fetch:** fetch_cache_not_found is not error ([3d1aa4e](https://github.com/AliMD/alwatr/commit/3d1aa4e572fbf4bc7b0a527a3fdcf4c521af18dd))
19
+ - **fetch:** fetch_failed error message ([3e98bd9](https://github.com/AliMD/alwatr/commit/3e98bd926a495c13d476f2f1cfb9e546a059d4d8))
20
+ - **fetch:** remove extra \_options ([ad24c81](https://github.com/AliMD/alwatr/commit/ad24c8104b944ebda52308e60d41976ac1eeee81))
21
+ - **fetch:** revalidateCallback issue ([7207909](https://github.com/AliMD/alwatr/commit/72079098edb438c28256dad03d7802bc2fab0858))
22
+ - set correct path ([d01ce6f](https://github.com/AliMD/alwatr/commit/d01ce6ffa749a5e3e0e11e35b4ed61d75d61fec9))
23
+ - **storage-engine:** AlwatrDocumentStorage ([ca9a7bf](https://github.com/AliMD/alwatr/commit/ca9a7bf5e17b333538e749ada5d481a06c847101))
24
+ - tsconfig ([e96dcd3](https://github.com/AliMD/alwatr/commit/e96dcd30774a9f06f7d051e0504192cbbe019e35))
25
+ - tsconfig refrences ([cea0562](https://github.com/AliMD/alwatr/commit/cea05621ecfa499476c5b10a412e60f27ba6a06d))
26
+
27
+ ### Features
28
+
29
+ - **fetch:** add AlwatrDocumentStorage type ([44b84f0](https://github.com/AliMD/alwatr/commit/44b84f0754169a707472655811020f6e542a6e5d))
30
+ - **fetch:** serviceRequest ([b0b5478](https://github.com/AliMD/alwatr/commit/b0b5478d16b2cb590cfc29d644006e4a459dd6d6))
31
+ - **fetch:** serviceRequest ([#513](https://github.com/AliMD/alwatr/issues/513)) ([113ee49](https://github.com/AliMD/alwatr/commit/113ee498c778d9efc00cc4807bfef09e52336a31))
32
+ - improve accident debugging ([d697e6c](https://github.com/AliMD/alwatr/commit/d697e6c4c7d0a4172f4dba9caf6fbd478f79de9c))
33
+ - improve error debugging ([1fba504](https://github.com/AliMD/alwatr/commit/1fba50400a1e8ececc10bbe8ea11cc8dcea2289c))
34
+
6
35
  # [0.25.0](https://github.com/AliMD/alwatr/compare/v0.24.1...v0.25.0) (2022-12-07)
7
36
 
8
37
  **Note:** Version bump only for package @alwatr/fetch
package/fetch.d.ts CHANGED
@@ -1,5 +1,9 @@
1
- import type { FetchOptions, CacheDuplicate, CacheStrategy, AlwatrDocumentObject, AlwatrServiceResponse } from './type';
2
- export { FetchOptions, CacheDuplicate, CacheStrategy, AlwatrDocumentObject, AlwatrServiceResponse, };
1
+ import type { FetchOptions, CacheDuplicate, CacheStrategy, AlwatrDocumentObject, AlwatrServiceResponse, AlwatrServiceResponseSuccessWithMeta, AlwatrServiceResponseSuccess } from './type.js';
2
+ export { FetchOptions, CacheDuplicate, CacheStrategy, AlwatrDocumentObject, AlwatrServiceResponse };
3
+ /**
4
+ * Fetch from alwatr services and return standard response.
5
+ */
6
+ export declare function serviceRequest<TData = Record<string, unknown>, TMeta = Record<string, unknown>>(options: FetchOptions): Promise<AlwatrServiceResponseSuccess<TData> | AlwatrServiceResponseSuccessWithMeta<TData, TMeta>>;
3
7
  /**
4
8
  * It's a wrapper around the browser's `fetch` function that adds retry pattern, timeout, cacheStrategy,
5
9
  * remove duplicates, etc.
@@ -17,5 +21,5 @@ export { FetchOptions, CacheDuplicate, CacheStrategy, AlwatrDocumentObject, Alwa
17
21
  * });
18
22
  * ```
19
23
  */
20
- export declare function fetch(_options: FetchOptions): Promise<Response>;
24
+ export declare function fetch(options: FetchOptions): Promise<Response>;
21
25
  //# sourceMappingURL=fetch.d.ts.map
package/fetch.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["src/fetch.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,YAAY,EACZ,cAAc,EACd,aAAa,EACb,oBAAoB,EACpB,qBAAqB,EACtB,MAAM,QAAQ,CAAC;AAEhB,OAAO,EACL,YAAY,EACZ,cAAc,EACd,aAAa,EACb,oBAAoB,EACpB,qBAAqB,GACtB,CAAC;AAcF;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,KAAK,CAAC,QAAQ,EAAE,YAAY,GAAG,OAAO,CAAC,QAAQ,CAAC,CAI/D"}
1
+ {"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["src/fetch.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,YAAY,EACZ,cAAc,EACd,aAAa,EACb,oBAAoB,EACpB,qBAAqB,EACrB,oCAAoC,EACpC,4BAA4B,EAC7B,MAAM,WAAW,CAAC;AAEnB,OAAO,EAAC,YAAY,EAAE,cAAc,EAAE,aAAa,EAAE,oBAAoB,EAAE,qBAAqB,EAAC,CAAC;AAclG;;GAEG;AACH,wBAAsB,cAAc,CAAC,KAAK,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,KAAK,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACjG,OAAO,EAAE,YAAY,GACtB,OAAO,CAAC,4BAA4B,CAAC,KAAK,CAAC,GAAG,oCAAoC,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CA8CnG;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,KAAK,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,QAAQ,CAAC,CAI9D"}
package/fetch.js CHANGED
@@ -7,6 +7,50 @@ alwatrRegisteredList.push({
7
7
  let alwatrCacheStorage;
8
8
  const cacheSupported = 'caches' in globalThis;
9
9
  const duplicateRequestStorage = {};
10
+ /**
11
+ * Fetch from alwatr services and return standard response.
12
+ */
13
+ export async function serviceRequest(options) {
14
+ logger.logMethod('serviceRequest');
15
+ let response;
16
+ try {
17
+ response = await fetch(options);
18
+ }
19
+ catch (err) {
20
+ logger.error('serviceRequest', err.message || 'fetch_failed', err, options);
21
+ throw err;
22
+ }
23
+ let responseText;
24
+ try {
25
+ responseText = await response.text();
26
+ }
27
+ catch (err) {
28
+ logger.error('serviceRequest', 'invalid_response', err, {
29
+ response,
30
+ });
31
+ throw err;
32
+ }
33
+ let responseJson;
34
+ try {
35
+ responseJson = JSON.parse(responseText);
36
+ }
37
+ catch (err) {
38
+ logger.error('serviceRequest', 'invalid_json', err, { responseText });
39
+ throw err;
40
+ }
41
+ if (responseJson.ok !== true) {
42
+ if (typeof responseJson.errorCode === 'string') {
43
+ logger.accident('serviceRequest', responseJson.errorCode, 'fetch response not ok', { responseJson });
44
+ throw new Error(responseJson.errorCode);
45
+ }
46
+ else {
47
+ logger.error('serviceRequest', 'fetch_nok', 'fetch response not ok', { responseJson });
48
+ throw new Error('fetch_nok');
49
+ }
50
+ }
51
+ // TODO: generate fetch signals hook (for easier handle loading and show error toast)
52
+ return responseJson;
53
+ }
10
54
  /**
11
55
  * It's a wrapper around the browser's `fetch` function that adds retry pattern, timeout, cacheStrategy,
12
56
  * remove duplicates, etc.
@@ -24,8 +68,8 @@ const duplicateRequestStorage = {};
24
68
  * });
25
69
  * ```
26
70
  */
27
- export function fetch(_options) {
28
- const options = _processOptions(_options);
71
+ export function fetch(options) {
72
+ options = _processOptions(options);
29
73
  logger.logMethodArgs('fetch', { options });
30
74
  return _handleCacheStrategy(options);
31
75
  }
@@ -42,7 +86,7 @@ function _processOptions(options) {
42
86
  (_f = options.cacheStrategy) !== null && _f !== void 0 ? _f : (options.cacheStrategy = 'network_only');
43
87
  (_g = options.removeDuplicate) !== null && _g !== void 0 ? _g : (options.removeDuplicate = 'never');
44
88
  if (options.cacheStrategy !== 'network_only' && cacheSupported !== true) {
45
- logger.accident('fetch', 'fetch_cache_strategy_ignore', 'Cache storage not support in this browser', {
89
+ logger.incident('fetch', 'fetch_cache_strategy_ignore', 'Cache storage not support in this browser', {
46
90
  cacheSupported,
47
91
  });
48
92
  options.cacheStrategy = 'network_only';
@@ -51,11 +95,11 @@ function _processOptions(options) {
51
95
  options.removeDuplicate = cacheSupported ? 'until_load' : 'always';
52
96
  }
53
97
  if (options.url.lastIndexOf('?') === -1 && options.queryParameters != null) {
98
+ const queryParameters = options.queryParameters;
54
99
  // prettier-ignore
55
100
  const queryArray = Object
56
- .keys(options.queryParameters)
57
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
58
- .map((key) => `${key}=${String(options.queryParameters[key])}`);
101
+ .keys(queryParameters)
102
+ .map((key) => `${key}=${String(queryParameters[key])}`);
59
103
  if (queryArray.length > 0) {
60
104
  options.url += '?' + queryArray.join('&');
61
105
  }
@@ -104,11 +148,12 @@ async function _handleCacheStrategy(options) {
104
148
  }
105
149
  case 'cache_only': {
106
150
  const cachedResponse = await cacheStorage.match(request);
107
- if (cachedResponse != null) {
108
- return cachedResponse;
151
+ if (cachedResponse == null) {
152
+ logger.accident('_handleCacheStrategy', 'fetch_cache_not_found', 'cacheStorage is cache_only but no cache found', { url: request.url });
153
+ throw new Error('fetch_cache_not_found');
109
154
  }
110
155
  // else
111
- throw new Error('fetch_cache_not_found');
156
+ return cachedResponse;
112
157
  }
113
158
  case 'network_first': {
114
159
  try {
@@ -132,8 +177,8 @@ async function _handleCacheStrategy(options) {
132
177
  const fetchedResponsePromise = _handleRemoveDuplicate(options).then((networkResponse) => {
133
178
  if (networkResponse.ok) {
134
179
  cacheStorage.put(request, networkResponse.clone());
135
- if (cachedResponse != null && typeof options.revalidateCallback === 'function') {
136
- options.revalidateCallback(networkResponse);
180
+ if (typeof options.revalidateCallback === 'function') {
181
+ setTimeout(options.revalidateCallback, 0, networkResponse.clone());
137
182
  }
138
183
  }
139
184
  return networkResponse;
@@ -176,7 +221,6 @@ async function _handleRemoveDuplicate(options) {
176
221
  * Handle retry pattern over `_handleTimeout`.
177
222
  */
178
223
  async function _handleRetryPattern(options) {
179
- var _a;
180
224
  if (!(options.retry > 1))
181
225
  return _handleTimeout(options);
182
226
  logger.logMethod('_handleRetryPattern');
@@ -191,7 +235,7 @@ async function _handleRetryPattern(options) {
191
235
  throw new Error('fetch_server_error');
192
236
  }
193
237
  catch (err) {
194
- logger.accident('fetch', (_a = err === null || err === void 0 ? void 0 : err.name) !== null && _a !== void 0 ? _a : 'fetch_failed', 'fetch failed and retry', { err });
238
+ logger.accident('fetch', 'fetch_failed_retry', (err === null || err === void 0 ? void 0 : err.message) || 'fetch failed and retry', err);
195
239
  await _wait(options.retryDelay);
196
240
  options.signal = externalAbortSignal;
197
241
  return _handleRetryPattern(options);
package/fetch.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.js","sourceRoot":"","sources":["src/fetch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,YAAY,EAAE,oBAAoB,EAAC,MAAM,gBAAgB,CAAC;AAkBlE,MAAM,MAAM,GAAG,YAAY,CAAC,cAAc,CAAC,CAAC;AAE5C,oBAAoB,CAAC,IAAI,CAAC;IACxB,IAAI,EAAE,eAAe;IACrB,OAAO,EAAE,oBAA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AAK,CAAC,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC;aAC3B,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;aACtC,KAAK,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;aACjC,OAAO,CAAC,GAAG,EAAE;YACZ,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC,sCAAsC;YAC7D,YAAY,CAAC,SAAS,CAAC,CAAC;QAC1B,CAAC,CAAC,CAAC;IACT,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,KAAK,GAAG,CAAC,EAAU,EAAiB,EAAE,CAAC,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC","sourcesContent":["import {createLogger, alwatrRegisteredList} from '@alwatr/logger';\n\nimport type {\n FetchOptions,\n CacheDuplicate,\n CacheStrategy,\n AlwatrDocumentObject,\n AlwatrServiceResponse,\n} from './type';\n\nexport {\n FetchOptions,\n CacheDuplicate,\n CacheStrategy,\n AlwatrDocumentObject,\n AlwatrServiceResponse,\n};\n\nconst logger = createLogger('alwatr/fetch');\n\nalwatrRegisteredList.push({\n name: '@alwatr/fetch',\n version: '{{ALWATR_VERSION}}',\n});\n\nlet alwatrCacheStorage: Cache;\nconst cacheSupported = 'caches' in globalThis;\n\nconst duplicateRequestStorage: Record<string, Promise<Response>> = {};\n\n/**\n * It's a wrapper around the browser's `fetch` function that adds retry pattern, timeout, cacheStrategy,\n * remove duplicates, etc.\n *\n * Example:\n *\n * ```ts\n * const response = await fetch({\n * url: '/api/products',\n * queryParameters: {limit: 10},\n * timeout: 10_000,\n * retry: 3,\n * cacheStrategy: 'stale_while_revalidate',\n * cacheDuplicate: 'auto',\n * });\n * ```\n */\nexport function fetch(_options: FetchOptions): Promise<Response> {\n const options = _processOptions(_options);\n logger.logMethodArgs('fetch', {options});\n return _handleCacheStrategy(options);\n}\n\n/**\n * Process fetch options and set defaults, etc.\n */\nfunction _processOptions(options: FetchOptions): Required<FetchOptions> {\n options.method ??= 'GET';\n options.window ??= null;\n\n options.timeout ??= 10_000;\n options.retry ??= 3;\n options.retryDelay ??= 1_000;\n options.cacheStrategy ??= 'network_only';\n options.removeDuplicate ??= 'never';\n\n if (options.cacheStrategy !== 'network_only' && cacheSupported !== true) {\n logger.accident('fetch', 'fetch_cache_strategy_ignore', 'Cache storage not support in this browser', {\n cacheSupported,\n });\n options.cacheStrategy = 'network_only';\n }\n\n if (options.removeDuplicate === 'auto') {\n options.removeDuplicate = cacheSupported ? 'until_load' : 'always';\n }\n\n if (options.url.lastIndexOf('?') === -1 && options.queryParameters != null) {\n // prettier-ignore\n const queryArray = Object\n .keys(options.queryParameters)\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n .map((key) => `${key}=${String(options.queryParameters![key])}`);\n\n if (queryArray.length > 0) {\n options.url += '?' + queryArray.join('&');\n }\n }\n\n if (options.bodyJson != null) {\n options.body = JSON.stringify(options.bodyJson);\n options.headers = {\n ...options.headers,\n 'Content-Type': 'application/json',\n };\n }\n\n if (options.token != null) {\n options.headers = {\n ...options.headers,\n Authorization: `Bearer ${options.token}`,\n };\n }\n\n return options as Required<FetchOptions>;\n}\n\n/**\n * Handle Cache Strategy over `_handleRemoveDuplicate`.\n */\nasync function _handleCacheStrategy(options: Required<FetchOptions>): Promise<Response> {\n if (options.cacheStrategy === 'network_only') {\n return _handleRemoveDuplicate(options);\n }\n // else handle cache strategies!\n logger.logMethod('_handleCacheStrategy');\n\n if (alwatrCacheStorage == null && options.cacheStorageName == null) {\n alwatrCacheStorage = await caches.open('alwatr_fetch_cache');\n }\n\n const cacheStorage =\n options.cacheStorageName != null ? await caches.open(options.cacheStorageName) : alwatrCacheStorage;\n\n const request = new Request(options.url, options);\n\n switch (options.cacheStrategy) {\n case 'cache_first': {\n const cachedResponse = await cacheStorage.match(request);\n if (cachedResponse != null) {\n return cachedResponse;\n }\n // else\n const response = await _handleRemoveDuplicate(options);\n if (response.ok) {\n cacheStorage.put(request, response.clone());\n }\n return response;\n }\n\n case 'cache_only': {\n const cachedResponse = await cacheStorage.match(request);\n if (cachedResponse != null) {\n return cachedResponse;\n }\n // else\n throw new Error('fetch_cache_not_found');\n }\n\n case 'network_first': {\n try {\n const networkResponse = await _handleRemoveDuplicate(options);\n if (networkResponse.ok) {\n cacheStorage.put(request, networkResponse.clone());\n }\n return networkResponse;\n }\n catch (err) {\n const cachedResponse = await cacheStorage.match(request);\n if (cachedResponse != null) {\n return cachedResponse;\n }\n // else\n throw err;\n }\n }\n\n case 'stale_while_revalidate': {\n const cachedResponse = await cacheStorage.match(request);\n const fetchedResponsePromise = _handleRemoveDuplicate(options).then((networkResponse) => {\n if (networkResponse.ok) {\n cacheStorage.put(request, networkResponse.clone());\n if (cachedResponse != null && typeof options.revalidateCallback === 'function') {\n options.revalidateCallback(networkResponse);\n }\n }\n return networkResponse;\n });\n\n return cachedResponse ?? fetchedResponsePromise;\n }\n\n default: {\n return _handleRemoveDuplicate(options);\n }\n }\n}\n\n/**\n * Handle Remove Duplicates over `_handleRetryPattern`.\n */\nasync function _handleRemoveDuplicate(options: Required<FetchOptions>): Promise<Response> {\n if (options.removeDuplicate === 'never') return _handleRetryPattern(options);\n\n logger.logMethod('_handleRemoveDuplicate');\n\n const cacheKey = options.method + ' ' + options.url;\n\n // We must cache fetch promise without await for handle other parallel requests.\n duplicateRequestStorage[cacheKey] ??= _handleRetryPattern(options);\n\n try {\n // For all requests need to await for clone responses.\n const response = await duplicateRequestStorage[cacheKey];\n\n if (duplicateRequestStorage[cacheKey] != null) {\n if (response.ok !== true || options.removeDuplicate === 'until_load') {\n delete duplicateRequestStorage[cacheKey];\n }\n }\n\n return response.clone();\n }\n catch (err) {\n // clean cache on any error.\n delete duplicateRequestStorage[cacheKey];\n throw err;\n }\n}\n\n/**\n * Handle retry pattern over `_handleTimeout`.\n */\nasync function _handleRetryPattern(options: Required<FetchOptions>): Promise<Response> {\n if (!(options.retry > 1)) return _handleTimeout(options);\n\n logger.logMethod('_handleRetryPattern');\n options.retry--;\n\n const externalAbortSignal = options.signal;\n\n try {\n const response = await _handleTimeout(options);\n\n if (response.status < 500) {\n return response;\n }\n // else\n throw new Error('fetch_server_error');\n }\n catch (err) {\n logger.accident('fetch', (err as Error)?.name ?? 'fetch_failed', 'fetch failed and retry', {err});\n\n await _wait(options.retryDelay);\n\n options.signal = externalAbortSignal;\n return _handleRetryPattern(options);\n }\n}\n\n/**\n * It's a wrapper around the browser's `fetch` with timeout.\n */\nfunction _handleTimeout(options: FetchOptions): Promise<Response> {\n if (options.timeout === 0) {\n return globalThis.fetch(options.url, options);\n }\n // else\n logger.logMethod('_handleTimeout');\n return new Promise((resolved, reject) => {\n // TODO: AbortController polyfill\n const abortController = new AbortController();\n const externalAbortSignal = options.signal;\n options.signal = abortController.signal;\n\n const timeoutId = setTimeout(() => {\n reject(new Error('fetch_timeout'));\n abortController.abort('fetch_timeout');\n }, options.timeout);\n\n if (externalAbortSignal != null) {\n // Respect external abort signal\n externalAbortSignal.addEventListener('abort', () => abortController.abort(), {once: true});\n }\n\n // abortController.signal.addEventListener('abort', () => {\n // logger.incident('fetch', 'fetch_abort_signal', 'fetch abort signal received', {\n // reason: abortController.signal.reason,\n // });\n // });\n\n globalThis\n .fetch(options.url, options)\n .then((response) => resolved(response))\n .catch((reason) => reject(reason))\n .finally(() => {\n delete options.signal; // try to avoid memory leak in nodejs!\n clearTimeout(timeoutId);\n });\n });\n}\n\nconst _wait = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n"]}
1
+ {"version":3,"file":"fetch.js","sourceRoot":"","sources":["src/fetch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,YAAY,EAAE,oBAAoB,EAAC,MAAM,gBAAgB,CAAC;AAclE,MAAM,MAAM,GAAG,YAAY,CAAC,cAAc,CAAC,CAAC;AAE5C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AC,CAAC;QACzC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;QAEpB,IAAI,mBAAmB,IAAI,IAAI,EAAE;YAC/B,gCAAgC;YAChC,mBAAmB,CAAC,gBAAgB,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,eAAe,CAAC,KAAK,EAAE,EAAE,EAAC,IAAI,EAAE,IAAI,EAAC,CAAC,CAAC;SAC5F;QAED,2DAA2D;QAC3D,oFAAoF;QACpF,6CAA6C;QAC7C,QAAQ;QACR,MAAM;QAEN,UAAU;aACL,KAAK,CAAC,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC;aAC3B,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;aACtC,KAAK,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;aACjC,OAAO,CAAC,GAAG,EAAE;YACZ,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC,sCAAsC;YAC7D,YAAY,CAAC,SAAS,CAAC,CAAC;QAC1B,CAAC,CAAC,CAAC;IACT,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,KAAK,GAAG,CAAC,EAAU,EAAiB,EAAE,CAAC,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC","sourcesContent":["import {createLogger, alwatrRegisteredList} from '@alwatr/logger';\n\nimport type {\n FetchOptions,\n CacheDuplicate,\n CacheStrategy,\n AlwatrDocumentObject,\n AlwatrServiceResponse,\n AlwatrServiceResponseSuccessWithMeta,\n AlwatrServiceResponseSuccess,\n} from './type.js';\n\nexport {FetchOptions, CacheDuplicate, CacheStrategy, AlwatrDocumentObject, AlwatrServiceResponse};\n\nconst logger = createLogger('alwatr/fetch');\n\nalwatrRegisteredList.push({\n name: '@alwatr/fetch',\n version: '{{ALWATR_VERSION}}',\n});\n\nlet alwatrCacheStorage: Cache;\nconst cacheSupported = 'caches' in globalThis;\n\nconst duplicateRequestStorage: Record<string, Promise<Response>> = {};\n\n/**\n * Fetch from alwatr services and return standard response.\n */\nexport async function serviceRequest<TData = Record<string, unknown>, TMeta = Record<string, unknown>>(\n options: FetchOptions,\n): Promise<AlwatrServiceResponseSuccess<TData> | AlwatrServiceResponseSuccessWithMeta<TData, TMeta>> {\n logger.logMethod('serviceRequest');\n\n let response: Response;\n try {\n response = await fetch(options);\n }\n catch (err) {\n logger.error('serviceRequest', (err as Error).message || 'fetch_failed', err, options);\n throw err;\n }\n\n let responseText: string;\n try {\n responseText = await response.text();\n }\n catch (err) {\n logger.error('serviceRequest', 'invalid_response', err, {\n response,\n });\n throw err;\n }\n\n let responseJson: AlwatrServiceResponse<TData, TMeta>;\n try {\n responseJson = JSON.parse(responseText);\n }\n catch (err) {\n logger.error('serviceRequest', 'invalid_json', err, {responseText});\n throw err;\n }\n\n if (responseJson.ok !== true) {\n if (typeof responseJson.errorCode === 'string') {\n logger.accident('serviceRequest', responseJson.errorCode, 'fetch response not ok', {responseJson});\n throw new Error(responseJson.errorCode);\n }\n else {\n logger.error('serviceRequest', 'fetch_nok', 'fetch response not ok', {responseJson});\n throw new Error('fetch_nok');\n }\n }\n\n // TODO: generate fetch signals hook (for easier handle loading and show error toast)\n\n return responseJson;\n}\n\n/**\n * It's a wrapper around the browser's `fetch` function that adds retry pattern, timeout, cacheStrategy,\n * remove duplicates, etc.\n *\n * Example:\n *\n * ```ts\n * const response = await fetch({\n * url: '/api/products',\n * queryParameters: {limit: 10},\n * timeout: 10_000,\n * retry: 3,\n * cacheStrategy: 'stale_while_revalidate',\n * cacheDuplicate: 'auto',\n * });\n * ```\n */\nexport function fetch(options: FetchOptions): Promise<Response> {\n options = _processOptions(options);\n logger.logMethodArgs('fetch', {options});\n return _handleCacheStrategy(options as Required<FetchOptions>);\n}\n\n/**\n * Process fetch options and set defaults, etc.\n */\nfunction _processOptions(options: FetchOptions): Required<FetchOptions> {\n options.method ??= 'GET';\n options.window ??= null;\n\n options.timeout ??= 10_000;\n options.retry ??= 3;\n options.retryDelay ??= 1_000;\n options.cacheStrategy ??= 'network_only';\n options.removeDuplicate ??= 'never';\n\n if (options.cacheStrategy !== 'network_only' && cacheSupported !== true) {\n logger.incident('fetch', 'fetch_cache_strategy_ignore', 'Cache storage not support in this browser', {\n cacheSupported,\n });\n options.cacheStrategy = 'network_only';\n }\n\n if (options.removeDuplicate === 'auto') {\n options.removeDuplicate = cacheSupported ? 'until_load' : 'always';\n }\n\n if (options.url.lastIndexOf('?') === -1 && options.queryParameters != null) {\n const queryParameters = options.queryParameters;\n // prettier-ignore\n const queryArray = Object\n .keys(queryParameters)\n .map((key) => `${key}=${String(queryParameters[key])}`);\n\n if (queryArray.length > 0) {\n options.url += '?' + queryArray.join('&');\n }\n }\n\n if (options.bodyJson != null) {\n options.body = JSON.stringify(options.bodyJson);\n options.headers = {\n ...options.headers,\n 'Content-Type': 'application/json',\n };\n }\n\n if (options.token != null) {\n options.headers = {\n ...options.headers,\n Authorization: `Bearer ${options.token}`,\n };\n }\n\n return options as Required<FetchOptions>;\n}\n\n/**\n * Handle Cache Strategy over `_handleRemoveDuplicate`.\n */\nasync function _handleCacheStrategy(options: Required<FetchOptions>): Promise<Response> {\n if (options.cacheStrategy === 'network_only') {\n return _handleRemoveDuplicate(options);\n }\n // else handle cache strategies!\n logger.logMethod('_handleCacheStrategy');\n\n if (alwatrCacheStorage == null && options.cacheStorageName == null) {\n alwatrCacheStorage = await caches.open('alwatr_fetch_cache');\n }\n\n const cacheStorage =\n options.cacheStorageName != null ? await caches.open(options.cacheStorageName) : alwatrCacheStorage;\n\n const request = new Request(options.url, options);\n\n switch (options.cacheStrategy) {\n case 'cache_first': {\n const cachedResponse = await cacheStorage.match(request);\n if (cachedResponse != null) {\n return cachedResponse;\n }\n // else\n const response = await _handleRemoveDuplicate(options);\n if (response.ok) {\n cacheStorage.put(request, response.clone());\n }\n return response;\n }\n\n case 'cache_only': {\n const cachedResponse = await cacheStorage.match(request);\n if (cachedResponse == null) {\n logger.accident(\n '_handleCacheStrategy',\n 'fetch_cache_not_found',\n 'cacheStorage is cache_only but no cache found',\n {url: request.url},\n );\n throw new Error('fetch_cache_not_found');\n }\n // else\n return cachedResponse;\n }\n\n case 'network_first': {\n try {\n const networkResponse = await _handleRemoveDuplicate(options);\n if (networkResponse.ok) {\n cacheStorage.put(request, networkResponse.clone());\n }\n return networkResponse;\n }\n catch (err) {\n const cachedResponse = await cacheStorage.match(request);\n if (cachedResponse != null) {\n return cachedResponse;\n }\n // else\n throw err;\n }\n }\n\n case 'stale_while_revalidate': {\n const cachedResponse = await cacheStorage.match(request);\n const fetchedResponsePromise = _handleRemoveDuplicate(options).then((networkResponse) => {\n if (networkResponse.ok) {\n cacheStorage.put(request, networkResponse.clone());\n if (typeof options.revalidateCallback === 'function') {\n setTimeout(options.revalidateCallback, 0, networkResponse.clone());\n }\n }\n return networkResponse;\n });\n\n return cachedResponse ?? fetchedResponsePromise;\n }\n\n default: {\n return _handleRemoveDuplicate(options);\n }\n }\n}\n\n/**\n * Handle Remove Duplicates over `_handleRetryPattern`.\n */\nasync function _handleRemoveDuplicate(options: Required<FetchOptions>): Promise<Response> {\n if (options.removeDuplicate === 'never') return _handleRetryPattern(options);\n\n logger.logMethod('_handleRemoveDuplicate');\n\n const cacheKey = options.method + ' ' + options.url;\n\n // We must cache fetch promise without await for handle other parallel requests.\n duplicateRequestStorage[cacheKey] ??= _handleRetryPattern(options);\n\n try {\n // For all requests need to await for clone responses.\n const response = await duplicateRequestStorage[cacheKey];\n\n if (duplicateRequestStorage[cacheKey] != null) {\n if (response.ok !== true || options.removeDuplicate === 'until_load') {\n delete duplicateRequestStorage[cacheKey];\n }\n }\n\n return response.clone();\n }\n catch (err) {\n // clean cache on any error.\n delete duplicateRequestStorage[cacheKey];\n throw err;\n }\n}\n\n/**\n * Handle retry pattern over `_handleTimeout`.\n */\nasync function _handleRetryPattern(options: Required<FetchOptions>): Promise<Response> {\n if (!(options.retry > 1)) return _handleTimeout(options);\n\n logger.logMethod('_handleRetryPattern');\n options.retry--;\n\n const externalAbortSignal = options.signal;\n\n try {\n const response = await _handleTimeout(options);\n\n if (response.status < 500) {\n return response;\n }\n // else\n throw new Error('fetch_server_error');\n }\n catch (err) {\n logger.accident('fetch', 'fetch_failed_retry', (err as Error)?.message || 'fetch failed and retry', err);\n\n await _wait(options.retryDelay);\n\n options.signal = externalAbortSignal;\n return _handleRetryPattern(options);\n }\n}\n\n/**\n * It's a wrapper around the browser's `fetch` with timeout.\n */\nfunction _handleTimeout(options: FetchOptions): Promise<Response> {\n if (options.timeout === 0) {\n return globalThis.fetch(options.url, options);\n }\n // else\n logger.logMethod('_handleTimeout');\n return new Promise((resolved, reject) => {\n // TODO: AbortController polyfill\n const abortController = new AbortController();\n const externalAbortSignal = options.signal;\n options.signal = abortController.signal;\n\n const timeoutId = setTimeout(() => {\n reject(new Error('fetch_timeout'));\n abortController.abort('fetch_timeout');\n }, options.timeout);\n\n if (externalAbortSignal != null) {\n // Respect external abort signal\n externalAbortSignal.addEventListener('abort', () => abortController.abort(), {once: true});\n }\n\n // abortController.signal.addEventListener('abort', () => {\n // logger.incident('fetch', 'fetch_abort_signal', 'fetch abort signal received', {\n // reason: abortController.signal.reason,\n // });\n // });\n\n globalThis\n .fetch(options.url, options)\n .then((response) => resolved(response))\n .catch((reason) => reject(reason))\n .finally(() => {\n delete options.signal; // try to avoid memory leak in nodejs!\n clearTimeout(timeoutId);\n });\n });\n}\n\nconst _wait = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alwatr/fetch",
3
- "version": "0.25.0",
3
+ "version": "0.26.1",
4
4
  "description": "Enhanced fetch API with cache strategy, retry pattern, timeout, helper methods and enhanced types written in tiny TypeScript, ES module.",
5
5
  "keywords": [
6
6
  "fetch",
@@ -27,15 +27,15 @@
27
27
  "repository": {
28
28
  "type": "git",
29
29
  "url": "https://github.com/AliMD/alwatr",
30
- "directory": "packages/core/fetch"
30
+ "directory": "core/fetch"
31
31
  },
32
- "homepage": "https://github.com/AliMD/alwatr/tree/main/packages/core/fetch#readme",
32
+ "homepage": "https://github.com/AliMD/alwatr/tree/main/core/fetch#readme",
33
33
  "bugs": {
34
34
  "url": "https://github.com/AliMD/alwatr/issues"
35
35
  },
36
36
  "dependencies": {
37
- "@alwatr/logger": "^0.25.0",
37
+ "@alwatr/logger": "^0.26.1",
38
38
  "tslib": "~2.4.1"
39
39
  },
40
- "gitHead": "03cf3c146f075309527bcf1e762a589696d0ce1d"
40
+ "gitHead": "73d4fc82563cd616ccb9b5b4ab7eb94870a4c51b"
41
41
  }
package/type.d.ts CHANGED
@@ -60,7 +60,7 @@ export interface FetchOptions extends RequestInit {
60
60
  /**
61
61
  * Revalidate callback for `stale_while_revalidate` cache strategy.
62
62
  */
63
- revalidateCallback?: (response: Response) => void;
63
+ revalidateCallback?: (response: Response) => void | Promise<void>;
64
64
  /**
65
65
  * Cache storage custom name.
66
66
  */
@@ -108,4 +108,11 @@ export type AlwatrServiceResponseSuccessWithMeta<TData = Record<string, unknown>
108
108
  data: TData;
109
109
  };
110
110
  export type AlwatrServiceResponse<TData = Record<string, unknown>, TMeta = Record<string, unknown>> = AlwatrServiceResponseSuccess<TData> | AlwatrServiceResponseSuccessWithMeta<TData, TMeta> | AlwatrServiceResponseFailed;
111
+ export type AlwatrDocumentMeta = {
112
+ formatVersion: number;
113
+ reversion: number;
114
+ lastUpdated: number;
115
+ lastAutoId: number;
116
+ };
117
+ export type AlwatrDocumentStorage<T extends AlwatrDocumentObject> = Omit<AlwatrServiceResponseSuccessWithMeta<Record<string, T>, AlwatrDocumentMeta>, 'statusCode' | 'errorCode'>;
111
118
  //# sourceMappingURL=type.d.ts.map
package/type.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"type.d.ts","sourceRoot":"","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GAAG;IAC/B,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,MAAM,MAAM,qBAAqB,CAAC,CAAC,SAAS,oBAAoB,IAAI,IAAI,CACtE,oCAAoC,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,EAAE,kBAAkB,CAAC,EAC3E,YAAY,GAAG,WAAW,CAC3B,CAAC"}
package/type.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"type.js","sourceRoot":"","sources":["src/type.ts"],"names":[],"mappings":"","sourcesContent":["export type Methods = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'TRACE' | 'OPTIONS' | 'PATCH';\nexport type CacheStrategy = 'network_only' | 'network_first' | 'cache_only' | 'cache_first' | 'stale_while_revalidate';\nexport type CacheDuplicate = 'never' | 'always' | 'until_load' | 'auto';\nexport type QueryParameters = Record<string, string | number | boolean>;\n\nexport interface FetchOptions extends RequestInit {\n /**\n * Request URL.\n */\n url: string;\n\n /**\n * A string to set request's method.\n *\n * @default 'GET'\n */\n method?: Methods;\n\n /**\n * A timeout for the fetch request.\n * Set `0` for disable it.\n *\n * Use with cation, you will have memory leak issue in nodejs.\n *\n * @default 10_000 ms\n */\n timeout?: number;\n\n /**\n * If fetch response not acceptable or timed out, it will retry the request.\n *\n * @default 3\n */\n retry?: number;\n\n /**\n * Delay before each retries.\n *\n * @default 1_000 ms\n */\n retryDelay?: number;\n\n /**\n * Simple memory caching for remove duplicate/parallel requests.\n *\n * - `never`: Never use memory caching.\n * - `always`: Always use memory caching and remove all duplicate requests.\n * - `until_load`: Cache parallel requests until request completed (it will be removed after the promise resolved).\n * - `auto`: If CacheStorage was supported use `until_load` strategy else use `always`.\n *\n * @default 'never'\n */\n removeDuplicate?: CacheDuplicate;\n\n /**\n * Strategies for caching.\n *\n * - `network_only`: Only network request without any cache.\n * - `network_first`: Network first, falling back to cache.\n * - `cache_only`: Cache only without any network request.\n * - `cache_first`: Cache first, falling back to network.\n * - `stale_while_revalidate`: Fastest strategy, Use cached first but always request network to update the cache.\n *\n * @default 'network_only'\n */\n cacheStrategy?: CacheStrategy;\n\n /**\n * Revalidate callback for `stale_while_revalidate` cache strategy.\n */\n revalidateCallback?: (response: Response) => void;\n\n /**\n * Cache storage custom name.\n */\n cacheStorageName?: string;\n\n /**\n * Body as JS Object.\n */\n bodyJson?: Record<string | number, unknown>;\n\n /**\n * URL Query Parameters as JS Object.\n */\n queryParameters?: QueryParameters;\n\n /**\n * Add token to Authentication bearer header.\n */\n token?: string;\n}\n\nexport type AlwatrDocumentObject = {\n id: string;\n meta?: {\n rev: number;\n created: number;\n updated: number;\n };\n};\n\nexport type AlwatrServiceResponseFailed = {\n ok: false;\n statusCode: number;\n errorCode: string;\n meta?: Record<string, unknown>;\n data?: never;\n};\n\nexport type AlwatrServiceResponseSuccess<TData = Record<string, unknown>> = {\n ok: true;\n statusCode?: number;\n errorCode?: never;\n meta?: never;\n data: TData;\n};\n\nexport type AlwatrServiceResponseSuccessWithMeta<TData = Record<string, unknown>, TMeta = Record<string, unknown>> = {\n ok: true;\n statusCode?: number;\n errorCode?: never;\n meta: TMeta;\n data: TData;\n};\n\nexport type AlwatrServiceResponse<TData = Record<string, unknown>, TMeta = Record<string, unknown>> =\n | AlwatrServiceResponseSuccess<TData>\n | AlwatrServiceResponseSuccessWithMeta<TData, TMeta>\n | AlwatrServiceResponseFailed;\n"]}
1
+ {"version":3,"file":"type.js","sourceRoot":"","sources":["src/type.ts"],"names":[],"mappings":"","sourcesContent":["export type Methods = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'TRACE' | 'OPTIONS' | 'PATCH';\nexport type CacheStrategy = 'network_only' | 'network_first' | 'cache_only' | 'cache_first' | 'stale_while_revalidate';\nexport type CacheDuplicate = 'never' | 'always' | 'until_load' | 'auto';\nexport type QueryParameters = Record<string, string | number | boolean>;\n\nexport interface FetchOptions extends RequestInit {\n /**\n * Request URL.\n */\n url: string;\n\n /**\n * A string to set request's method.\n *\n * @default 'GET'\n */\n method?: Methods;\n\n /**\n * A timeout for the fetch request.\n * Set `0` for disable it.\n *\n * Use with cation, you will have memory leak issue in nodejs.\n *\n * @default 10_000 ms\n */\n timeout?: number;\n\n /**\n * If fetch response not acceptable or timed out, it will retry the request.\n *\n * @default 3\n */\n retry?: number;\n\n /**\n * Delay before each retries.\n *\n * @default 1_000 ms\n */\n retryDelay?: number;\n\n /**\n * Simple memory caching for remove duplicate/parallel requests.\n *\n * - `never`: Never use memory caching.\n * - `always`: Always use memory caching and remove all duplicate requests.\n * - `until_load`: Cache parallel requests until request completed (it will be removed after the promise resolved).\n * - `auto`: If CacheStorage was supported use `until_load` strategy else use `always`.\n *\n * @default 'never'\n */\n removeDuplicate?: CacheDuplicate;\n\n /**\n * Strategies for caching.\n *\n * - `network_only`: Only network request without any cache.\n * - `network_first`: Network first, falling back to cache.\n * - `cache_only`: Cache only without any network request.\n * - `cache_first`: Cache first, falling back to network.\n * - `stale_while_revalidate`: Fastest strategy, Use cached first but always request network to update the cache.\n *\n * @default 'network_only'\n */\n cacheStrategy?: CacheStrategy;\n\n /**\n * Revalidate callback for `stale_while_revalidate` cache strategy.\n */\n revalidateCallback?: (response: Response) => void | Promise<void>;\n\n /**\n * Cache storage custom name.\n */\n cacheStorageName?: string;\n\n /**\n * Body as JS Object.\n */\n bodyJson?: Record<string | number, unknown>;\n\n /**\n * URL Query Parameters as JS Object.\n */\n queryParameters?: QueryParameters;\n\n /**\n * Add token to Authentication bearer header.\n */\n token?: string;\n}\n\nexport type AlwatrDocumentObject = {\n id: string;\n meta?: {\n rev: number;\n created: number;\n updated: number;\n };\n};\n\nexport type AlwatrServiceResponseFailed = {\n ok: false;\n statusCode: number;\n errorCode: string;\n meta?: Record<string, unknown>;\n data?: never;\n};\n\nexport type AlwatrServiceResponseSuccess<TData = Record<string, unknown>> = {\n ok: true;\n statusCode?: number;\n errorCode?: never;\n meta?: never;\n data: TData;\n};\n\nexport type AlwatrServiceResponseSuccessWithMeta<TData = Record<string, unknown>, TMeta = Record<string, unknown>> = {\n ok: true;\n statusCode?: number;\n errorCode?: never;\n meta: TMeta;\n data: TData;\n};\n\nexport type AlwatrServiceResponse<TData = Record<string, unknown>, TMeta = Record<string, unknown>> =\n | AlwatrServiceResponseSuccess<TData>\n | AlwatrServiceResponseSuccessWithMeta<TData, TMeta>\n | AlwatrServiceResponseFailed;\n\nexport type AlwatrDocumentMeta = {\n formatVersion: number;\n reversion: number;\n lastUpdated: number;\n lastAutoId: number;\n};\n\nexport type AlwatrDocumentStorage<T extends AlwatrDocumentObject> = Omit<\n AlwatrServiceResponseSuccessWithMeta<Record<string, T>, AlwatrDocumentMeta>,\n 'statusCode' | 'errorCode'\n>;\n"]}