@alwatr/fetch 0.27.0 → 0.29.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/CHANGELOG.md CHANGED
@@ -3,6 +3,28 @@
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.29.0](https://github.com/AliMD/alwatr/compare/v0.28.0...v0.29.0) (2023-02-10)
7
+
8
+ ### Bug Fixes
9
+
10
+ - **fetch:** device id to client id ([077e467](https://github.com/AliMD/alwatr/commit/077e4671d804d43c8f61a9d163d8d51d7a69134e))
11
+ - **fetch:** headers type ([cd4b14e](https://github.com/AliMD/alwatr/commit/cd4b14e46b5090b6df8cb4f89d22b53966b9151e))
12
+
13
+ ### Features
14
+
15
+ - **fetch:** add update_cache to CacheStrategy ([e1406b1](https://github.com/AliMD/alwatr/commit/e1406b12e1276de3295c47506c8102ab3f8bfa79))
16
+ - **fetch:** clientId on service request ([9575a1d](https://github.com/AliMD/alwatr/commit/9575a1d595a0a4757581a29a66837cbe4be46ed3))
17
+
18
+ # [0.28.0](https://github.com/AliMD/alwatr/compare/v0.27.0...v0.28.0) (2023-01-20)
19
+
20
+ ### Bug Fixes
21
+
22
+ - review issue ([e5d192c](https://github.com/AliMD/alwatr/commit/e5d192cbee6917c2de01146cf8bd026895724ab8))
23
+
24
+ ### Features
25
+
26
+ - **type:** add types ([2de3842](https://github.com/AliMD/alwatr/commit/2de384297b70b9818ec8d62ce8d31be4822d95a4))
27
+
6
28
  # [0.27.0](https://github.com/AliMD/alwatr/compare/v0.26.0...v0.27.0) (2022-12-29)
7
29
 
8
30
  **Note:** Version bump only for package @alwatr/fetch
package/fetch.d.ts CHANGED
@@ -1,9 +1,10 @@
1
- import type { FetchOptions, CacheDuplicate, CacheStrategy, AlwatrDocumentObject, AlwatrServiceResponse, AlwatrServiceResponseSuccessWithMeta, AlwatrServiceResponseSuccess } from './type.js';
2
- export { FetchOptions, CacheDuplicate, CacheStrategy, AlwatrDocumentObject, AlwatrServiceResponse };
1
+ import type { FetchOptions, CacheDuplicate, CacheStrategy } from './type.js';
2
+ import type { AlwatrServiceResponse, AlwatrServiceResponseSuccessWithMeta, AlwatrServiceResponseSuccess, StringifyableRecord } from '@alwatr/type';
3
+ export type { FetchOptions, CacheDuplicate, CacheStrategy, AlwatrServiceResponse, AlwatrServiceResponseSuccessWithMeta, AlwatrServiceResponseSuccess, };
3
4
  /**
4
5
  * Fetch from alwatr services and return standard response.
5
6
  */
6
- export declare function serviceRequest<TData = Record<string, unknown>, TMeta = Record<string, unknown>>(options: FetchOptions): Promise<AlwatrServiceResponseSuccess<TData> | AlwatrServiceResponseSuccessWithMeta<TData, TMeta>>;
7
+ export declare function serviceRequest<TData extends StringifyableRecord = StringifyableRecord, TMeta extends StringifyableRecord = StringifyableRecord>(options: FetchOptions): Promise<AlwatrServiceResponseSuccess<TData> | AlwatrServiceResponseSuccessWithMeta<TData, TMeta>>;
7
8
  /**
8
9
  * It's a wrapper around the browser's `fetch` function that adds retry pattern, timeout, cacheStrategy,
9
10
  * remove duplicates, etc.
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,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"}
1
+ {"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["src/fetch.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAC,YAAY,EAAE,cAAc,EAAE,aAAa,EAAC,MAAM,WAAW,CAAC;AAC3E,OAAO,KAAK,EACV,qBAAqB,EACrB,oCAAoC,EACpC,4BAA4B,EAC5B,mBAAmB,EACpB,MAAM,cAAc,CAAC;AAEtB,YAAY,EACV,YAAY,EACZ,cAAc,EACd,aAAa,EACb,qBAAqB,EACrB,oCAAoC,EACpC,4BAA4B,GAC7B,CAAC;AAcF;;GAEG;AACH,wBAAsB,cAAc,CAClC,KAAK,SAAS,mBAAmB,GAAG,mBAAmB,EACvD,KAAK,SAAS,mBAAmB,GAAG,mBAAmB,EAErD,OAAO,EAAE,YAAY,GACtB,OAAO,CAAC,4BAA4B,CAAC,KAAK,CAAC,GAAG,oCAAoC,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAmDnG;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,KAAK,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,QAAQ,CAAC,CAI9D"}
package/fetch.js CHANGED
@@ -1,8 +1,9 @@
1
- import { createLogger, alwatrRegisteredList } from '@alwatr/logger';
1
+ import { createLogger, globalAlwatr } from '@alwatr/logger';
2
+ import { getClientId } from '@alwatr/math';
2
3
  const logger = createLogger('alwatr/fetch');
3
- alwatrRegisteredList.push({
4
+ globalAlwatr.registeredList.push({
4
5
  name: '@alwatr/fetch',
5
- version: '{{ALWATR_VERSION}}',
6
+ version: _ALWATR_VERSION_,
6
7
  });
7
8
  let alwatrCacheStorage;
8
9
  const cacheSupported = 'caches' in globalThis;
@@ -11,7 +12,12 @@ const duplicateRequestStorage = {};
11
12
  * Fetch from alwatr services and return standard response.
12
13
  */
13
14
  export async function serviceRequest(options) {
15
+ var _a;
14
16
  logger.logMethod('serviceRequest');
17
+ (_a = options.headers) !== null && _a !== void 0 ? _a : (options.headers = {});
18
+ if (!options.headers['client-id']) {
19
+ options.headers['client-id'] = getClientId();
20
+ }
15
21
  let response;
16
22
  try {
17
23
  response = await fetch(options);
@@ -77,7 +83,7 @@ export function fetch(options) {
77
83
  * Process fetch options and set defaults, etc.
78
84
  */
79
85
  function _processOptions(options) {
80
- var _a, _b, _c, _d, _e, _f, _g;
86
+ var _a, _b, _c, _d, _e, _f, _g, _h;
81
87
  (_a = options.method) !== null && _a !== void 0 ? _a : (options.method = 'GET');
82
88
  (_b = options.window) !== null && _b !== void 0 ? _b : (options.window = null);
83
89
  (_c = options.timeout) !== null && _c !== void 0 ? _c : (options.timeout = 10000);
@@ -85,6 +91,7 @@ function _processOptions(options) {
85
91
  (_e = options.retryDelay) !== null && _e !== void 0 ? _e : (options.retryDelay = 1000);
86
92
  (_f = options.cacheStrategy) !== null && _f !== void 0 ? _f : (options.cacheStrategy = 'network_only');
87
93
  (_g = options.removeDuplicate) !== null && _g !== void 0 ? _g : (options.removeDuplicate = 'never');
94
+ (_h = options.headers) !== null && _h !== void 0 ? _h : (options.headers = {});
88
95
  if (options.cacheStrategy !== 'network_only' && cacheSupported !== true) {
89
96
  logger.incident('fetch', 'fetch_cache_strategy_ignore', 'Cache storage not support in this browser', {
90
97
  cacheSupported,
@@ -106,16 +113,10 @@ function _processOptions(options) {
106
113
  }
107
114
  if (options.bodyJson != null) {
108
115
  options.body = JSON.stringify(options.bodyJson);
109
- options.headers = {
110
- ...options.headers,
111
- 'Content-Type': 'application/json',
112
- };
116
+ options.headers['Content-Type'] = 'application/json';
113
117
  }
114
118
  if (options.token != null) {
115
- options.headers = {
116
- ...options.headers,
117
- Authorization: `Bearer ${options.token}`,
118
- };
119
+ options.headers.Authorization = `Bearer ${options.token}`;
119
120
  }
120
121
  return options;
121
122
  }
@@ -172,6 +173,13 @@ async function _handleCacheStrategy(options) {
172
173
  throw err;
173
174
  }
174
175
  }
176
+ case 'update_cache': {
177
+ const networkResponse = await _handleRemoveDuplicate(options);
178
+ if (networkResponse.ok) {
179
+ cacheStorage.put(request, networkResponse.clone());
180
+ }
181
+ return networkResponse;
182
+ }
175
183
  case 'stale_while_revalidate': {
176
184
  const cachedResponse = await cacheStorage.match(request);
177
185
  const fetchedResponsePromise = _handleRemoveDuplicate(options).then((networkResponse) => {
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;AAclE,MAAM,MAAM,GAAG,YAAY,CAAC,cAAc,CAAC,CAAC;AAE5C,oBAAoB,CAAC,IAAI,CAAC;IACxB,IAAI,EAAE,eAAe;IACrB,OAAO,EAAE,oBAAoB;CAC9B,CAAC,CAAC;AAEH,IAAI,kBAAyB,CAAC;AAC9B,MAAM,cAAc,GAAG,QAAQ,IAAI,UAAU,CAAC;AAE9C,MAAM,uBAAuB,GAAsC,EAAE,CAAC;AAEtE;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAChC,OAAqB;IAEvB,MAAM,CAAC,SAAS,CAAC,gBAAgB,CAAC,CAAC;IAEnC,IAAI,QAAkB,CAAC;IACvB,IAAI;QACF,QAAQ,GAAG,MAAM,KAAK,CAAC,OAAO,CAAC,CAAC;KACjC;IACD,OAAO,GAAG,EAAE;QACV,MAAM,CAAC,KAAK,CAAC,gBAAgB,EAAG,GAAa,CAAC,OAAO,IAAI,cAAc,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;QACvF,MAAM,GAAG,CAAC;KACX;IAED,IAAI,YAAoB,CAAC;IACzB,IAAI;QACF,YAAY,GAAG,MAAM,Q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C,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"]}
1
+ {"version":3,"file":"fetch.js","sourceRoot":"","sources":["src/fetch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,YAAY,EAAE,YAAY,EAAC,MAAM,gBAAgB,CAAC;AAC1D,OAAO,EAAC,WAAW,EAAC,MAAM,cAAc,CAAC;AAmBzC,MAAM,MAAM,GAAG,YAAY,CAAC,cAAc,CAAC,CAAC;AAE5C,YAAY,CAAC,cAAc,CAAC,IAAI,CAAC;IAC/B,IAAI,EAAE,eAAe;IACrB,OAAO,EAAE,gBAAgB;CAC1B,CAAC,CAAC;AAEH,IAAI,kBAAyB,CAAC;AAC9B,MAAM,cAAc,GAAG,QAAQ,IAAI,UAAU,CAAC;AAE9C,MAAM,uBAAuB,GAAsC,EAAE,CAAC;AAEtE;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAIhC,OAAqB;;IAEvB,MAAM,CAAC,SAAS,CAAC,gBAAgB,CAAC,CAAC;IAEnC,MAAA,OAAO,CAAC,OAAO,oCAAf,OAAO,CAAC,OAAO,GAAK,EAAE,EAAC;IACvB,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,WAAW,CAAC,EAAE;QACjC,OAAO,CAAC,OAAO,CAAC,WAAW,CAAC,GAAG,WAAW,EAAE,CAAC;KAC9C;IAED,IAAI,QAAkB,CAAC;IACvB,IAAI;QACF,QAAQ,GAAG,MAAM,KAAK,CAAC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AAG,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, globalAlwatr} from '@alwatr/logger';\nimport {getClientId} from '@alwatr/math';\n\nimport type {FetchOptions, CacheDuplicate, CacheStrategy} from './type.js';\nimport type {\n AlwatrServiceResponse,\n AlwatrServiceResponseSuccessWithMeta,\n AlwatrServiceResponseSuccess,\n StringifyableRecord,\n} from '@alwatr/type';\n\nexport type {\n FetchOptions,\n CacheDuplicate,\n CacheStrategy,\n AlwatrServiceResponse,\n AlwatrServiceResponseSuccessWithMeta,\n AlwatrServiceResponseSuccess,\n};\n\nconst logger = createLogger('alwatr/fetch');\n\nglobalAlwatr.registeredList.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<\n TData extends StringifyableRecord = StringifyableRecord,\n TMeta extends StringifyableRecord = StringifyableRecord,\n>(\n options: FetchOptions,\n): Promise<AlwatrServiceResponseSuccess<TData> | AlwatrServiceResponseSuccessWithMeta<TData, TMeta>> {\n logger.logMethod('serviceRequest');\n\n options.headers ??= {};\n if (!options.headers['client-id']) {\n options.headers['client-id'] = getClientId();\n }\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 options.headers ??= {};\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['Content-Type'] = 'application/json';\n }\n\n if (options.token != null) {\n options.headers.Authorization = `Bearer ${options.token}`;\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 'update_cache': {\n const networkResponse = await _handleRemoveDuplicate(options);\n if (networkResponse.ok) {\n cacheStorage.put(request, networkResponse.clone());\n }\n return networkResponse;\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.27.0",
3
+ "version": "0.29.0",
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",
@@ -34,8 +34,12 @@
34
34
  "url": "https://github.com/AliMD/alwatr/issues"
35
35
  },
36
36
  "dependencies": {
37
- "@alwatr/logger": "^0.27.0",
38
- "tslib": "~2.4.1"
37
+ "@alwatr/logger": "^0.29.0",
38
+ "@alwatr/math": "^0.29.0",
39
+ "tslib": "^2.5.0"
39
40
  },
40
- "gitHead": "f6612d969fe49af71ab27e75fa54601071953141"
41
+ "devDependencies": {
42
+ "@alwatr/type": "^0.29.0"
43
+ },
44
+ "gitHead": "801487f183f8afd8cba25e0fec5d508c0b4fe809"
41
45
  }
package/type.d.ts CHANGED
@@ -1,7 +1,6 @@
1
- export type Methods = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'TRACE' | 'OPTIONS' | 'PATCH';
2
- export type CacheStrategy = 'network_only' | 'network_first' | 'cache_only' | 'cache_first' | 'stale_while_revalidate';
1
+ import type { Methods, QueryParameters } from '@alwatr/type';
2
+ export type CacheStrategy = 'network_only' | 'network_first' | 'cache_only' | 'cache_first' | 'update_cache' | 'stale_while_revalidate';
3
3
  export type CacheDuplicate = 'never' | 'always' | 'until_load' | 'auto';
4
- export type QueryParameters = Record<string, string | number | boolean>;
5
4
  export interface FetchOptions extends RequestInit {
6
5
  /**
7
6
  * Request URL.
@@ -13,6 +12,10 @@ export interface FetchOptions extends RequestInit {
13
12
  * @default 'GET'
14
13
  */
15
14
  method?: Methods;
15
+ /**
16
+ * A Headers object to set request's headers.
17
+ */
18
+ headers?: Record<string, string>;
16
19
  /**
17
20
  * A timeout for the fetch request.
18
21
  * Set `0` for disable it.
@@ -52,6 +55,7 @@ export interface FetchOptions extends RequestInit {
52
55
  * - `network_first`: Network first, falling back to cache.
53
56
  * - `cache_only`: Cache only without any network request.
54
57
  * - `cache_first`: Cache first, falling back to network.
58
+ * - `update_cache`: Like `network_only` but with update cache.
55
59
  * - `stale_while_revalidate`: Fastest strategy, Use cached first but always request network to update the cache.
56
60
  *
57
61
  * @default 'network_only'
@@ -78,41 +82,4 @@ export interface FetchOptions extends RequestInit {
78
82
  */
79
83
  token?: string;
80
84
  }
81
- export type AlwatrDocumentObject = {
82
- id: string;
83
- meta?: {
84
- rev: number;
85
- created: number;
86
- updated: number;
87
- };
88
- };
89
- export type AlwatrServiceResponseFailed = {
90
- ok: false;
91
- statusCode: number;
92
- errorCode: string;
93
- meta?: Record<string, unknown>;
94
- data?: never;
95
- };
96
- export type AlwatrServiceResponseSuccess<TData = Record<string, unknown>> = {
97
- ok: true;
98
- statusCode?: number;
99
- errorCode?: never;
100
- meta?: never;
101
- data: TData;
102
- };
103
- export type AlwatrServiceResponseSuccessWithMeta<TData = Record<string, unknown>, TMeta = Record<string, unknown>> = {
104
- ok: true;
105
- statusCode?: number;
106
- errorCode?: never;
107
- meta: TMeta;
108
- data: TData;
109
- };
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'>;
118
85
  //# sourceMappingURL=type.d.ts.map
package/type.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"type.d.ts","sourceRoot":"","sources":["src/type.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,OAAO,GAAG,KAAK,GAAG,MAAM,GAAG,MAAM,GAAG,KAAK,GAAG,QAAQ,GAAG,SAAS,GAAG,OAAO,GAAG,SAAS,GAAG,OAAO,CAAC;AAC7G,MAAM,MAAM,aAAa,GAAG,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CAAC;IAElC;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB"}
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 | 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"]}
1
+ {"version":3,"file":"type.js","sourceRoot":"","sources":["src/type.ts"],"names":[],"mappings":"","sourcesContent":["import type {Methods, QueryParameters} from '@alwatr/type';\n\nexport type CacheStrategy =\n | 'network_only'\n | 'network_first'\n | 'cache_only'\n | 'cache_first'\n | 'update_cache'\n | 'stale_while_revalidate';\n\nexport type CacheDuplicate = 'never' | 'always' | 'until_load' | 'auto';\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 Headers object to set request's headers.\n */\n headers?: Record<string, string>;\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 * - `update_cache`: Like `network_only` but with update cache.\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"]}