api-def 0.9.0 → 0.9.2

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 (121) hide show
  1. package/cjs/Api.d.ts +35 -35
  2. package/cjs/Api.js +140 -144
  3. package/cjs/ApiConstants.d.ts +58 -58
  4. package/cjs/ApiConstants.js +55 -55
  5. package/cjs/ApiTypes.d.ts +103 -103
  6. package/cjs/ApiTypes.js +4 -4
  7. package/cjs/ApiUtils.d.ts +6 -6
  8. package/cjs/ApiUtils.js +51 -53
  9. package/cjs/Endpoint.d.ts +52 -52
  10. package/cjs/Endpoint.js +104 -108
  11. package/cjs/EndpointBuilder.d.ts +14 -14
  12. package/cjs/EndpointBuilder.js +46 -46
  13. package/cjs/MockingTypes.d.ts +30 -30
  14. package/cjs/MockingTypes.js +2 -2
  15. package/cjs/QueryHandling.d.ts +3 -3
  16. package/cjs/QueryHandling.js +24 -24
  17. package/cjs/RequestConfig.d.ts +2 -2
  18. package/cjs/RequestConfig.js +74 -74
  19. package/cjs/RequestContext.d.ts +48 -48
  20. package/cjs/RequestContext.js +235 -238
  21. package/cjs/RequestError.d.ts +30 -30
  22. package/cjs/RequestError.js +47 -47
  23. package/cjs/Requester.d.ts +3 -3
  24. package/cjs/Requester.js +335 -336
  25. package/cjs/TextDecoding.d.ts +1 -1
  26. package/cjs/TextDecoding.js +152 -139
  27. package/cjs/UtilTypes.d.ts +5 -5
  28. package/cjs/UtilTypes.js +2 -2
  29. package/cjs/Utils.d.ts +15 -15
  30. package/cjs/Utils.js +79 -77
  31. package/cjs/Validation.d.ts +8 -8
  32. package/cjs/Validation.js +2 -2
  33. package/cjs/backend/AxiosRequestBackend.d.ts +13 -13
  34. package/cjs/backend/AxiosRequestBackend.js +99 -99
  35. package/cjs/backend/FetchRequestBackend.d.ts +15 -15
  36. package/cjs/backend/FetchRequestBackend.js +202 -197
  37. package/cjs/backend/MockRequestBackend.d.ts +11 -11
  38. package/cjs/backend/MockRequestBackend.js +164 -164
  39. package/cjs/backend/RequestBackend.d.ts +19 -19
  40. package/cjs/backend/RequestBackend.js +2 -2
  41. package/cjs/cache/CacheBackend.d.ts +6 -6
  42. package/cjs/cache/CacheBackend.js +2 -2
  43. package/cjs/cache/Caching.d.ts +10 -10
  44. package/cjs/cache/Caching.js +88 -88
  45. package/cjs/cache/LocalForageCacheBackend.d.ts +9 -9
  46. package/cjs/cache/LocalForageCacheBackend.js +24 -24
  47. package/cjs/cache/LocalStorageCacheBackend.d.ts +7 -7
  48. package/cjs/cache/LocalStorageCacheBackend.js +77 -77
  49. package/cjs/index.d.ts +13 -13
  50. package/cjs/index.js +41 -41
  51. package/cjs/middleware/CacheMiddleware.d.ts +7 -7
  52. package/cjs/middleware/CacheMiddleware.js +107 -107
  53. package/cjs/middleware/LoggingMiddleware.d.ts +6 -6
  54. package/cjs/middleware/LoggingMiddleware.js +82 -88
  55. package/cjs/util/retry/index.d.ts +3 -3
  56. package/cjs/util/retry/index.js +52 -52
  57. package/cjs/util/retry/lib/retry.d.ts +3 -3
  58. package/cjs/util/retry/lib/retry.js +50 -54
  59. package/cjs/util/retry/lib/retryOperation.d.ts +27 -27
  60. package/cjs/util/retry/lib/retryOperation.js +130 -134
  61. package/esm/Api.d.ts +35 -35
  62. package/esm/Api.js +92 -98
  63. package/esm/ApiConstants.d.ts +58 -58
  64. package/esm/ApiConstants.js +52 -52
  65. package/esm/ApiTypes.d.ts +103 -103
  66. package/esm/ApiTypes.js +1 -1
  67. package/esm/ApiUtils.d.ts +6 -6
  68. package/esm/ApiUtils.js +43 -45
  69. package/esm/Endpoint.d.ts +52 -52
  70. package/esm/Endpoint.js +66 -70
  71. package/esm/EndpointBuilder.d.ts +14 -14
  72. package/esm/EndpointBuilder.js +31 -31
  73. package/esm/MockingTypes.d.ts +30 -30
  74. package/esm/MockingTypes.js +1 -1
  75. package/esm/QueryHandling.d.ts +3 -3
  76. package/esm/QueryHandling.js +19 -19
  77. package/esm/RequestConfig.d.ts +2 -2
  78. package/esm/RequestConfig.js +56 -56
  79. package/esm/RequestContext.d.ts +48 -48
  80. package/esm/RequestContext.js +167 -170
  81. package/esm/RequestError.d.ts +30 -30
  82. package/esm/RequestError.js +42 -42
  83. package/esm/Requester.d.ts +3 -3
  84. package/esm/Requester.js +252 -253
  85. package/esm/TextDecoding.d.ts +1 -1
  86. package/esm/TextDecoding.js +148 -135
  87. package/esm/UtilTypes.d.ts +5 -5
  88. package/esm/UtilTypes.js +1 -1
  89. package/esm/Utils.d.ts +15 -15
  90. package/esm/Utils.js +66 -68
  91. package/esm/Validation.d.ts +8 -8
  92. package/esm/Validation.js +1 -1
  93. package/esm/backend/AxiosRequestBackend.d.ts +13 -13
  94. package/esm/backend/AxiosRequestBackend.js +62 -62
  95. package/esm/backend/FetchRequestBackend.d.ts +15 -15
  96. package/esm/backend/FetchRequestBackend.js +136 -126
  97. package/esm/backend/MockRequestBackend.d.ts +11 -11
  98. package/esm/backend/MockRequestBackend.js +116 -116
  99. package/esm/backend/RequestBackend.d.ts +19 -19
  100. package/esm/backend/RequestBackend.js +1 -1
  101. package/esm/cache/CacheBackend.d.ts +6 -6
  102. package/esm/cache/CacheBackend.js +1 -1
  103. package/esm/cache/Caching.d.ts +10 -10
  104. package/esm/cache/Caching.js +39 -39
  105. package/esm/cache/LocalForageCacheBackend.d.ts +9 -9
  106. package/esm/cache/LocalForageCacheBackend.js +20 -20
  107. package/esm/cache/LocalStorageCacheBackend.d.ts +7 -7
  108. package/esm/cache/LocalStorageCacheBackend.js +32 -32
  109. package/esm/index.d.ts +13 -13
  110. package/esm/index.js +14 -15
  111. package/esm/middleware/CacheMiddleware.d.ts +7 -7
  112. package/esm/middleware/CacheMiddleware.js +58 -58
  113. package/esm/middleware/LoggingMiddleware.d.ts +6 -6
  114. package/esm/middleware/LoggingMiddleware.js +77 -83
  115. package/esm/util/retry/index.d.ts +3 -3
  116. package/esm/util/retry/index.js +50 -50
  117. package/esm/util/retry/lib/retry.d.ts +3 -3
  118. package/esm/util/retry/lib/retry.js +35 -39
  119. package/esm/util/retry/lib/retryOperation.d.ts +27 -27
  120. package/esm/util/retry/lib/retryOperation.js +126 -132
  121. package/package.json +12 -32
@@ -1,58 +1,58 @@
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 * as Caching from "../cache/Caching";
11
- import { CacheSource, EventResultType, RequestEvent, RequestMethod } from "../ApiConstants";
12
- const CacheMiddleware = (options = {}) => {
13
- return {
14
- [RequestEvent.Success]: (context) => __awaiter(void 0, void 0, void 0, function* () {
15
- if (context.method !== RequestMethod.Get)
16
- return;
17
- const { cache } = context.computedConfig || {};
18
- const shouldCache = !options.predicate || options.predicate();
19
- if (cache && shouldCache) {
20
- const expiry = typeof cache === "number" ? cache : (options.defaultExpiry || Caching.DEFAULT_CACHE_EXPIRY);
21
- yield Caching.setCachedItem(context.key, context.response, expiry);
22
- }
23
- }),
24
- [RequestEvent.BeforeSend]: (context) => __awaiter(void 0, void 0, void 0, function* () {
25
- if (context.method !== RequestMethod.Get)
26
- return;
27
- const { cache } = context.computedConfig || {};
28
- const shouldCache = !options.predicate || options.predicate();
29
- if (cache && shouldCache) {
30
- if (cache) {
31
- const cachedValue = yield Caching.getCachedItem(context.key);
32
- if (cachedValue) {
33
- context.stats.cached = {
34
- is: true,
35
- by: CacheSource.Local,
36
- };
37
- context.cacheInfo.source = CacheSource.Local;
38
- context.cacheInfo.cached = true;
39
- return {
40
- type: EventResultType.Respond,
41
- response: cachedValue,
42
- };
43
- }
44
- }
45
- }
46
- if (cache === false) {
47
- context.updateQuery({
48
- _bust: Math.floor(Math.random() * 9000) + 1000,
49
- });
50
- context.updateHeaders({
51
- Pragma: "no-cache, no-store, must-revalidate",
52
- "Cache-Control": "no-cache, no-store, must-revalidate",
53
- });
54
- }
55
- }),
56
- };
57
- };
58
- export default CacheMiddleware;
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 { CacheSource, EventResultType, RequestEvent, RequestMethod } from "../ApiConstants";
11
+ import * as Caching from "../cache/Caching";
12
+ const CacheMiddleware = (options = {}) => {
13
+ return {
14
+ [RequestEvent.Success]: (context) => __awaiter(void 0, void 0, void 0, function* () {
15
+ if (context.method !== RequestMethod.Get)
16
+ return;
17
+ const { cache } = context.computedConfig || {};
18
+ const shouldCache = !options.predicate || options.predicate();
19
+ if (cache && shouldCache) {
20
+ const expiry = typeof cache === "number" ? cache : options.defaultExpiry || Caching.DEFAULT_CACHE_EXPIRY;
21
+ yield Caching.setCachedItem(context.key, context.response, expiry);
22
+ }
23
+ }),
24
+ [RequestEvent.BeforeSend]: (context) => __awaiter(void 0, void 0, void 0, function* () {
25
+ if (context.method !== RequestMethod.Get)
26
+ return;
27
+ const { cache } = context.computedConfig || {};
28
+ const shouldCache = !options.predicate || options.predicate();
29
+ if (cache && shouldCache) {
30
+ if (cache) {
31
+ const cachedValue = yield Caching.getCachedItem(context.key);
32
+ if (cachedValue) {
33
+ context.stats.cached = {
34
+ is: true,
35
+ by: CacheSource.Local,
36
+ };
37
+ context.cacheInfo.source = CacheSource.Local;
38
+ context.cacheInfo.cached = true;
39
+ return {
40
+ type: EventResultType.Respond,
41
+ response: cachedValue,
42
+ };
43
+ }
44
+ }
45
+ }
46
+ if (cache === false) {
47
+ context.updateQuery({
48
+ _bust: Math.floor(Math.random() * 9000) + 1000,
49
+ });
50
+ context.updateHeaders({
51
+ Pragma: "no-cache, no-store, must-revalidate",
52
+ "Cache-Control": "no-cache, no-store, must-revalidate",
53
+ });
54
+ }
55
+ }),
56
+ };
57
+ };
58
+ export default CacheMiddleware;
@@ -1,6 +1,6 @@
1
- import { RequestMiddleware } from "../ApiTypes";
2
- export interface LoggingMiddlewareOptions {
3
- predicate?: () => boolean;
4
- }
5
- declare const LoggingMiddleware: (config?: LoggingMiddlewareOptions) => RequestMiddleware;
6
- export default LoggingMiddleware;
1
+ import { RequestMiddleware } from "../ApiTypes";
2
+ export interface LoggingMiddlewareOptions {
3
+ predicate?: () => boolean;
4
+ }
5
+ declare const LoggingMiddleware: (config?: LoggingMiddlewareOptions) => RequestMiddleware;
6
+ export default LoggingMiddleware;
@@ -1,83 +1,77 @@
1
- import * as ApiUtils from "../ApiUtils";
2
- import * as Utils from "../Utils";
3
- import { RequestEvent } from "../ApiConstants";
4
- var LogType;
5
- (function (LogType) {
6
- LogType[LogType["Info"] = 0] = "Info";
7
- LogType[LogType["Success"] = 1] = "Success";
8
- LogType[LogType["Error"] = 2] = "Error";
9
- LogType[LogType["Warn"] = 3] = "Warn";
10
- })(LogType || (LogType = {}));
11
- const COLOR_MAP = {
12
- [LogType.Error]: "#c8646c",
13
- [LogType.Info]: "#85a6c7",
14
- [LogType.Success]: "#a9c490",
15
- [LogType.Warn]: "#d19a66",
16
- };
17
- const diagnoseError = (error) => {
18
- if (!error.response) {
19
- if (ApiUtils.isNetworkError(error)) {
20
- return { message: "network issue", error };
21
- }
22
- if (ApiUtils.isCancelledError(error)) {
23
- return { message: "cancelled", error };
24
- }
25
- return { message: "client-side error", error };
26
- }
27
- const { status, data } = error.response;
28
- const code = data === null || data === void 0 ? void 0 : data.code;
29
- return {
30
- message: `responded with ${status}${code ? ` (${code})` : ""}`,
31
- response: error.response,
32
- };
33
- };
34
- const formatTime = (time) => {
35
- return `${Utils.padNumber(time.getHours(), 2)}:${Utils.padNumber(time.getMinutes(), 2)}:${Utils.padNumber(time.getSeconds(), 2)}.${Utils.padNumber(time.getMilliseconds(), 3)}`;
36
- };
37
- const log = (context, type, message, config, objects) => {
38
- if (typeof config.predicate === "function" && !config.predicate()) {
39
- return;
40
- }
41
- const color = COLOR_MAP[type];
42
- const timestamp = formatTime(new Date());
43
- const args = [
44
- `%cnetwork %c[${context.api.name}] ${context.method.toUpperCase()} ${context.path} %c${message} %c@ ${timestamp}`,
45
- "color:gray",
46
- "color:auto",
47
- `color:${color}`,
48
- "color:gray",
49
- ];
50
- /* eslint-disable-next-line no-console */
51
- console.groupCollapsed(...args);
52
- /* eslint-disable-next-line no-console */
53
- console.log(Utils.assign({ context: context }, objects || {}));
54
- /* eslint-disable-next-line no-console */
55
- console.groupEnd();
56
- };
57
- const LoggingMiddleware = (config = {}) => {
58
- return {
59
- [RequestEvent.BeforeSend]: (context) => {
60
- log(context, LogType.Info, context.stats.attempt > 1 ? "retrying" : "sending", config);
61
- },
62
- [RequestEvent.Success]: (context) => {
63
- var _a;
64
- const cacheSource = context.cacheInfo.source;
65
- log(context, LogType.Success, `responded with ${(_a = context.response) === null || _a === void 0 ? void 0 : _a.status}${cacheSource ? ` (cached by ${cacheSource})` : ""}`, config);
66
- },
67
- [RequestEvent.Error]: (context) => {
68
- if (context.error) {
69
- const { error, message } = diagnoseError(context.error);
70
- log(context, LogType.Warn, `error on attempt ${context.stats.attempt} - ${message}`, config, { error: error });
71
- }
72
- },
73
- [RequestEvent.UnrecoverableError]: (context) => {
74
- if (context.error) {
75
- const { error, message } = diagnoseError(context.error);
76
- log(context, LogType.Error, `failed - ${message}`, config, {
77
- error: error,
78
- });
79
- }
80
- },
81
- };
82
- };
83
- export default LoggingMiddleware;
1
+ import { RequestEvent } from "../ApiConstants";
2
+ import * as ApiUtils from "../ApiUtils";
3
+ import * as Utils from "../Utils";
4
+ var LogType;
5
+ (function (LogType) {
6
+ LogType[LogType["Info"] = 0] = "Info";
7
+ LogType[LogType["Success"] = 1] = "Success";
8
+ LogType[LogType["Error"] = 2] = "Error";
9
+ LogType[LogType["Warn"] = 3] = "Warn";
10
+ })(LogType || (LogType = {}));
11
+ const COLOR_MAP = {
12
+ [LogType.Error]: "#c8646c",
13
+ [LogType.Info]: "#85a6c7",
14
+ [LogType.Success]: "#a9c490",
15
+ [LogType.Warn]: "#d19a66",
16
+ };
17
+ const diagnoseError = (error) => {
18
+ if (!error.response) {
19
+ if (ApiUtils.isNetworkError(error)) {
20
+ return { message: "network issue", error };
21
+ }
22
+ if (ApiUtils.isCancelledError(error)) {
23
+ return { message: "cancelled", error };
24
+ }
25
+ return { message: "client-side error", error };
26
+ }
27
+ const { status, data } = error.response;
28
+ const code = data === null || data === void 0 ? void 0 : data.code;
29
+ return {
30
+ message: `responded with ${status}${code ? ` (${code})` : ""}`,
31
+ response: error.response,
32
+ };
33
+ };
34
+ const formatTime = (time) => {
35
+ return `${Utils.padNumber(time.getHours(), 2)}:${Utils.padNumber(time.getMinutes(), 2)}:${Utils.padNumber(time.getSeconds(), 2)}.${Utils.padNumber(time.getMilliseconds(), 3)}`;
36
+ };
37
+ const log = (context, type, message, config, objects) => {
38
+ if (typeof config.predicate === "function" && !config.predicate()) {
39
+ return;
40
+ }
41
+ const color = COLOR_MAP[type];
42
+ const timestamp = formatTime(new Date());
43
+ const args = [`%cnetwork %c[${context.api.name}] ${context.method.toUpperCase()} ${context.path} %c${message} %c@ ${timestamp}`, "color:gray", "color:auto", `color:${color}`, "color:gray"];
44
+ /* eslint-disable-next-line no-console */
45
+ console.groupCollapsed(...args);
46
+ /* eslint-disable-next-line no-console */
47
+ console.log(Utils.assign({ context: context }, objects || {}));
48
+ /* eslint-disable-next-line no-console */
49
+ console.groupEnd();
50
+ };
51
+ const LoggingMiddleware = (config = {}) => {
52
+ return {
53
+ [RequestEvent.BeforeSend]: (context) => {
54
+ log(context, LogType.Info, context.stats.attempt > 1 ? "retrying" : "sending", config);
55
+ },
56
+ [RequestEvent.Success]: (context) => {
57
+ var _a;
58
+ const cacheSource = context.cacheInfo.source;
59
+ log(context, LogType.Success, `responded with ${(_a = context.response) === null || _a === void 0 ? void 0 : _a.status}${cacheSource ? ` (cached by ${cacheSource})` : ""}`, config);
60
+ },
61
+ [RequestEvent.Error]: (context) => {
62
+ if (context.error) {
63
+ const { error, message } = diagnoseError(context.error);
64
+ log(context, LogType.Warn, `error on attempt ${context.stats.attempt} - ${message}`, config, { error: error });
65
+ }
66
+ },
67
+ [RequestEvent.UnrecoverableError]: (context) => {
68
+ if (context.error) {
69
+ const { error, message } = diagnoseError(context.error);
70
+ log(context, LogType.Error, `failed - ${message}`, config, {
71
+ error: error,
72
+ });
73
+ }
74
+ },
75
+ };
76
+ };
77
+ export default LoggingMiddleware;
@@ -1,3 +1,3 @@
1
- import { RetryFunction, RetryOptions } from "./interfaces";
2
- declare const retry: <A>(fn: RetryFunction<A>, opts: RetryOptions) => Promise<A>;
3
- export default retry;
1
+ import { RetryFunction, RetryOptions } from "./interfaces";
2
+ declare const retry: <A>(fn: RetryFunction<A>, opts: RetryOptions) => Promise<A>;
3
+ export default retry;
@@ -1,50 +1,50 @@
1
- import * as retrier from "./lib/retry";
2
- // Retry is just transplanted from here:
3
- // https://www.npmjs.com/package/retry (lib), and
4
- // https://www.npmjs.com/package/async-retry (RetryFunction)
5
- // ---
6
- const retry = (fn, opts) => {
7
- return new Promise((resolve, reject) => {
8
- const options = opts || {};
9
- if (!("randomize" in options)) {
10
- options.randomize = true;
11
- }
12
- const op = retrier.operation(options);
13
- // We allow the user to abort retrying
14
- // this makes sense in the cases where
15
- // knowledge is obtained that retrying
16
- // would be futile (e.g.: auth errors)
17
- const bail = (err) => {
18
- reject(err || new Error("Aborted"));
19
- };
20
- const onError = (err, num) => {
21
- if (err.bail) {
22
- bail(err);
23
- return;
24
- }
25
- if (!op.retry(err)) {
26
- reject(op.mainError());
27
- }
28
- else if (options.onRetry) {
29
- options.onRetry(err, num);
30
- }
31
- };
32
- const runAttempt = (num) => {
33
- let val;
34
- try {
35
- val = fn(bail, num);
36
- }
37
- catch (err) {
38
- onError(err, num);
39
- return;
40
- }
41
- Promise.resolve(val)
42
- .then(resolve)
43
- .catch(function catchIt(err) {
44
- onError(err, num);
45
- });
46
- };
47
- op.attempt(runAttempt);
48
- });
49
- };
50
- export default retry;
1
+ import * as retrier from "./lib/retry";
2
+ // Retry is just transplanted from here:
3
+ // https://www.npmjs.com/package/retry (lib), and
4
+ // https://www.npmjs.com/package/async-retry (RetryFunction)
5
+ // ---
6
+ const retry = (fn, opts) => {
7
+ return new Promise((resolve, reject) => {
8
+ const options = opts || {};
9
+ if (!("randomize" in options)) {
10
+ options.randomize = true;
11
+ }
12
+ const op = retrier.operation(options);
13
+ // We allow the user to abort retrying
14
+ // this makes sense in the cases where
15
+ // knowledge is obtained that retrying
16
+ // would be futile (e.g.: auth errors)
17
+ const bail = (err) => {
18
+ reject(err || new Error("Aborted"));
19
+ };
20
+ const onError = (err, num) => {
21
+ if (err.bail) {
22
+ bail(err);
23
+ return;
24
+ }
25
+ if (!op.retry(err)) {
26
+ reject(op.mainError());
27
+ }
28
+ else if (options.onRetry) {
29
+ options.onRetry(err, num);
30
+ }
31
+ };
32
+ const runAttempt = (num) => {
33
+ let val;
34
+ try {
35
+ val = fn(bail, num);
36
+ }
37
+ catch (err) {
38
+ onError(err, num);
39
+ return;
40
+ }
41
+ Promise.resolve(val)
42
+ .then(resolve)
43
+ .catch(function catchIt(err) {
44
+ onError(err, num);
45
+ });
46
+ };
47
+ op.attempt(runAttempt);
48
+ });
49
+ };
50
+ export default retry;
@@ -1,3 +1,3 @@
1
- import { RetryOptions } from "../interfaces";
2
- import RetryOperation from "./retryOperation";
3
- export declare const operation: (options: RetryOptions) => RetryOperation;
1
+ import { RetryOptions } from "../interfaces";
2
+ import RetryOperation from "./retryOperation";
3
+ export declare const operation: (options: RetryOptions) => RetryOperation;
@@ -1,39 +1,35 @@
1
- import RetryOperation from "./retryOperation";
2
- export const operation = (options) => {
3
- const timeouts = _timeouts(options);
4
- return (new RetryOperation(timeouts, {
5
- forever: options && (options.forever || options.retries === Infinity),
6
- unref: options && options.unref,
7
- maxRetryTime: options && options.maxRetryTime,
8
- }));
9
- };
10
- const _timeouts = (options) => {
11
- var _a;
12
- const createTimeout = (attempt, opts) => {
13
- const random = (opts.randomize)
14
- ? (Math.random() + 1)
15
- : 1;
16
- let timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));
17
- timeout = Math.min(timeout, opts.maxTimeout);
18
- return (timeout);
19
- };
20
- const defaultRetries = 10;
21
- const opts = Object.assign({ retries: defaultRetries, factor: 2, minTimeout: 1 * 1000, maxTimeout: Infinity, randomize: false }, options);
22
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
23
- if (opts.minTimeout > opts.maxTimeout) {
24
- throw new Error("minTimeout is greater than maxTimeout");
25
- }
26
- const timeouts = [];
27
- const numRetries = (_a = opts.retries) !== null && _a !== void 0 ? _a : defaultRetries;
28
- for (let i = 0; i < numRetries; i++) {
29
- timeouts.push(createTimeout(i, opts));
30
- }
31
- if (options && options.forever && !timeouts.length) {
32
- timeouts.push(createTimeout(numRetries, opts));
33
- }
34
- // sort the array numerically ascending
35
- timeouts.sort(function (a, b) {
36
- return a - b;
37
- });
38
- return (timeouts);
39
- };
1
+ import RetryOperation from "./retryOperation";
2
+ export const operation = (options) => {
3
+ const timeouts = _timeouts(options);
4
+ return new RetryOperation(timeouts, {
5
+ forever: options && (options.forever || options.retries === Infinity),
6
+ unref: options === null || options === void 0 ? void 0 : options.unref,
7
+ maxRetryTime: options === null || options === void 0 ? void 0 : options.maxRetryTime,
8
+ });
9
+ };
10
+ const _timeouts = (options) => {
11
+ var _a;
12
+ const createTimeout = (attempt, opts) => {
13
+ const random = opts.randomize ? Math.random() + 1 : 1;
14
+ let timeout = Math.round(random * Math.max(opts.minTimeout, 1) * opts.factor ** attempt);
15
+ timeout = Math.min(timeout, opts.maxTimeout);
16
+ return timeout;
17
+ };
18
+ const defaultRetries = 10;
19
+ const opts = Object.assign({ retries: defaultRetries, factor: 2, minTimeout: 1 * 1000, maxTimeout: Infinity, randomize: false }, options);
20
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
21
+ if (opts.minTimeout > opts.maxTimeout) {
22
+ throw new Error("minTimeout is greater than maxTimeout");
23
+ }
24
+ const timeouts = [];
25
+ const numRetries = (_a = opts.retries) !== null && _a !== void 0 ? _a : defaultRetries;
26
+ for (let i = 0; i < numRetries; i++) {
27
+ timeouts.push(createTimeout(i, opts));
28
+ }
29
+ if ((options === null || options === void 0 ? void 0 : options.forever) && !timeouts.length) {
30
+ timeouts.push(createTimeout(numRetries, opts));
31
+ }
32
+ // sort the array numerically ascending
33
+ timeouts.sort((a, b) => a - b);
34
+ return timeouts;
35
+ };
@@ -1,27 +1,27 @@
1
- export default RetryOperation;
2
- declare function RetryOperation(timeouts: any, options: any): void;
3
- declare class RetryOperation {
4
- constructor(timeouts: any, options: any);
5
- _originalTimeouts: any;
6
- _timeouts: any;
7
- _options: any;
8
- _maxRetryTime: any;
9
- _fn: any;
10
- _errors: any[];
11
- _attempts: number;
12
- _operationTimeout: any;
13
- _operationTimeoutCb: any;
14
- _timeout: NodeJS.Timeout | null;
15
- _operationStart: number | null;
16
- _timer: NodeJS.Timeout | null;
17
- _cachedTimeouts: any;
18
- reset(): void;
19
- stop(): void;
20
- retry(err: any): boolean;
21
- attempt(fn: any, timeoutOps: any): void;
22
- try(fn: any): void;
23
- start: (fn: any) => void;
24
- errors(): any[];
25
- attempts(): number;
26
- mainError(): any;
27
- }
1
+ export default RetryOperation;
2
+ declare function RetryOperation(timeouts: any, options: any): void;
3
+ declare class RetryOperation {
4
+ constructor(timeouts: any, options: any);
5
+ _originalTimeouts: any;
6
+ _timeouts: any;
7
+ _options: any;
8
+ _maxRetryTime: any;
9
+ _fn: any;
10
+ _errors: any[];
11
+ _attempts: number;
12
+ _operationTimeout: any;
13
+ _operationTimeoutCb: any;
14
+ _timeout: NodeJS.Timeout | null;
15
+ _operationStart: number | null;
16
+ _timer: NodeJS.Timeout | null;
17
+ _cachedTimeouts: any;
18
+ reset(): void;
19
+ stop(): void;
20
+ retry(err: any): boolean;
21
+ attempt(fn: any, timeoutOps: any): void;
22
+ try(fn: any): void;
23
+ start: (fn: any) => void;
24
+ errors(): any[];
25
+ attempts(): number;
26
+ mainError(): any;
27
+ }