typescript-retry-decorator 2.0.0 → 2.0.5

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/.eslintrc.js CHANGED
@@ -1,4 +1,5 @@
1
1
  module.exports = {
2
+ root: true,
2
3
  parser: '@typescript-eslint/parser', // Specifies the ESLint parser
3
4
  plugins: ["@typescript-eslint"],
4
5
  extends: [
@@ -8,7 +8,7 @@ on:
8
8
  types: [created]
9
9
 
10
10
  jobs:
11
- build:
11
+ publish-npm:
12
12
  runs-on: ubuntu-latest
13
13
  strategy:
14
14
  matrix:
@@ -18,22 +18,10 @@ jobs:
18
18
  - uses: actions/setup-node@v2
19
19
  with:
20
20
  node-version: ${{ matrix.node-version }}
21
+ registry-url: https://registry.npmjs.org/
21
22
  - run: npm ci
22
23
  - run: npm run build
23
24
  - run: npm test
24
-
25
- publish-npm:
26
- needs: build
27
- runs-on: ubuntu-latest
28
- strategy:
29
- matrix:
30
- node-version: [12.x]
31
- steps:
32
- - uses: actions/checkout@v2
33
- - uses: actions/setup-node@v2
34
- with:
35
- node-version: ${{ matrix.node-version }}
36
- registry-url: https://registry.npmjs.org/
37
25
  - run: npm publish
38
26
  env:
39
- NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
27
+ NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=example.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"example.d.ts","sourceRoot":"","sources":["../src/example.ts"],"names":[],"mappings":""}
@@ -0,0 +1,165 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
12
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
13
+ return new (P || (P = Promise))(function (resolve, reject) {
14
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
15
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
16
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
17
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
18
+ });
19
+ };
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ const retry_decorator_1 = require("./retry.decorator");
22
+ let count = 1;
23
+ class RetryExample {
24
+ static noDelayRetry() {
25
+ return __awaiter(this, void 0, void 0, function* () {
26
+ console.info(`Calling noDelayRetry for the ${count++} time at ${new Date().toLocaleTimeString()}`);
27
+ throw new Error('I failed!');
28
+ });
29
+ }
30
+ static noDelaySpecificRetry() {
31
+ return __awaiter(this, void 0, void 0, function* () {
32
+ console.info(`Calling noDelayRetry for the ${count++} time at ${new Date().toLocaleTimeString()}`);
33
+ throw new SyntaxError('I failed with SyntaxError!');
34
+ });
35
+ }
36
+ static doRetry() {
37
+ return __awaiter(this, void 0, void 0, function* () {
38
+ console.info(`Calling doRetry for the ${count++} time at ${new Date().toLocaleTimeString()}`);
39
+ throw new Error('Error: 429');
40
+ });
41
+ }
42
+ static doNotRetry() {
43
+ return __awaiter(this, void 0, void 0, function* () {
44
+ console.info(`Calling doNotRetry for the ${count++} time at ${new Date().toLocaleTimeString()}`);
45
+ throw new Error('Error: 404');
46
+ });
47
+ }
48
+ static fixedBackOffRetry() {
49
+ return __awaiter(this, void 0, void 0, function* () {
50
+ console.info(`Calling fixedBackOffRetry 1s for the ${count++} time at ${new Date().toLocaleTimeString()}`);
51
+ throw new Error('I failed!');
52
+ });
53
+ }
54
+ static ExponentialBackOffRetry() {
55
+ return __awaiter(this, void 0, void 0, function* () {
56
+ console.info(`Calling ExponentialBackOffRetry backOff 1s, multiplier=3 for the ${count++} time at ${new Date().toLocaleTimeString()}`);
57
+ throw new Error('I failed!');
58
+ });
59
+ }
60
+ }
61
+ __decorate([
62
+ (0, retry_decorator_1.Retryable)({ maxAttempts: 3 }),
63
+ __metadata("design:type", Function),
64
+ __metadata("design:paramtypes", []),
65
+ __metadata("design:returntype", Promise)
66
+ ], RetryExample, "noDelayRetry", null);
67
+ __decorate([
68
+ (0, retry_decorator_1.Retryable)({ maxAttempts: 3, value: [SyntaxError, ReferenceError] }),
69
+ __metadata("design:type", Function),
70
+ __metadata("design:paramtypes", []),
71
+ __metadata("design:returntype", Promise)
72
+ ], RetryExample, "noDelaySpecificRetry", null);
73
+ __decorate([
74
+ (0, retry_decorator_1.Retryable)({
75
+ maxAttempts: 3,
76
+ backOff: 1000,
77
+ doRetry: (e) => {
78
+ return e.message === 'Error: 429';
79
+ },
80
+ }),
81
+ __metadata("design:type", Function),
82
+ __metadata("design:paramtypes", []),
83
+ __metadata("design:returntype", Promise)
84
+ ], RetryExample, "doRetry", null);
85
+ __decorate([
86
+ (0, retry_decorator_1.Retryable)({
87
+ maxAttempts: 3,
88
+ backOff: 1000,
89
+ doRetry: (e) => {
90
+ return e.message === 'Error: 429';
91
+ },
92
+ }),
93
+ __metadata("design:type", Function),
94
+ __metadata("design:paramtypes", []),
95
+ __metadata("design:returntype", Promise)
96
+ ], RetryExample, "doNotRetry", null);
97
+ __decorate([
98
+ (0, retry_decorator_1.Retryable)({
99
+ maxAttempts: 3,
100
+ backOffPolicy: retry_decorator_1.BackOffPolicy.FixedBackOffPolicy,
101
+ backOff: 1000,
102
+ }),
103
+ __metadata("design:type", Function),
104
+ __metadata("design:paramtypes", []),
105
+ __metadata("design:returntype", Promise)
106
+ ], RetryExample, "fixedBackOffRetry", null);
107
+ __decorate([
108
+ (0, retry_decorator_1.Retryable)({
109
+ maxAttempts: 3,
110
+ backOffPolicy: retry_decorator_1.BackOffPolicy.ExponentialBackOffPolicy,
111
+ backOff: 1000,
112
+ exponentialOption: { maxInterval: 4000, multiplier: 3 },
113
+ }),
114
+ __metadata("design:type", Function),
115
+ __metadata("design:paramtypes", []),
116
+ __metadata("design:returntype", Promise)
117
+ ], RetryExample, "ExponentialBackOffRetry", null);
118
+ (() => __awaiter(void 0, void 0, void 0, function* () {
119
+ try {
120
+ resetCount();
121
+ yield RetryExample.noDelayRetry();
122
+ }
123
+ catch (e) {
124
+ console.info(`All retry done as expected, final message: '${e.message}'`);
125
+ }
126
+ try {
127
+ resetCount();
128
+ yield RetryExample.noDelaySpecificRetry();
129
+ }
130
+ catch (e) {
131
+ console.info(`All retry done as expected, final message: '${e.message}'`);
132
+ }
133
+ try {
134
+ resetCount();
135
+ yield RetryExample.doRetry();
136
+ }
137
+ catch (e) {
138
+ console.info(`All retry done as expected, final message: '${e.message}'`);
139
+ }
140
+ try {
141
+ resetCount();
142
+ yield RetryExample.doNotRetry();
143
+ }
144
+ catch (e) {
145
+ console.info(`All retry done as expected, final message: '${e.message}'`);
146
+ }
147
+ try {
148
+ resetCount();
149
+ yield RetryExample.fixedBackOffRetry();
150
+ }
151
+ catch (e) {
152
+ console.info(`All retry done as expected, final message: '${e.message}'`);
153
+ }
154
+ try {
155
+ resetCount();
156
+ yield RetryExample.ExponentialBackOffRetry();
157
+ }
158
+ catch (e) {
159
+ console.info(`All retry done as expected, final message: '${e.message}'`);
160
+ }
161
+ }))();
162
+ function resetCount() {
163
+ count = 1;
164
+ }
165
+ //# sourceMappingURL=example.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"example.js","sourceRoot":"","sources":["../src/example.ts"],"names":[],"mappings":";;;;;;;;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O,GAAG,CAAC,CAAC;KAC3E;IAED,IAAI;QACF,UAAU,EAAE,CAAC;QACb,MAAM,YAAY,CAAC,oBAAoB,EAAE,CAAC;KAC3C;IAAC,OAAO,CAAC,EAAE;QACV,OAAO,CAAC,IAAI,CAAC,+CAA+C,CAAC,CAAC,OAAO,GAAG,CAAC,CAAC;KAC3E;IAED,IAAI;QACF,UAAU,EAAE,CAAC;QACb,MAAM,YAAY,CAAC,OAAO,EAAE,CAAC;KAC9B;IAAC,OAAO,CAAC,EAAE;QACV,OAAO,CAAC,IAAI,CAAC,+CAA+C,CAAC,CAAC,OAAO,GAAG,CAAC,CAAC;KAC3E;IAED,IAAI;QACF,UAAU,EAAE,CAAC;QACb,MAAM,YAAY,CAAC,UAAU,EAAE,CAAC;KACjC;IAAC,OAAO,CAAC,EAAE;QACV,OAAO,CAAC,IAAI,CAAC,+CAA+C,CAAC,CAAC,OAAO,GAAG,CAAC,CAAC;KAC3E;IAED,IAAI;QACF,UAAU,EAAE,CAAC;QACb,MAAM,YAAY,CAAC,iBAAiB,EAAE,CAAC;KACxC;IAAC,OAAO,CAAC,EAAE;QACV,OAAO,CAAC,IAAI,CAAC,+CAA+C,CAAC,CAAC,OAAO,GAAG,CAAC,CAAC;KAC3E;IAED,IAAI;QACF,UAAU,EAAE,CAAC;QACb,MAAM,YAAY,CAAC,uBAAuB,EAAE,CAAC;KAC9C;IAAC,OAAO,CAAC,EAAE;QACV,OAAO,CAAC,IAAI,CAAC,+CAA+C,CAAC,CAAC,OAAO,GAAG,CAAC,CAAC;KAC3E;AAEH,CAAC,CAAA,CAAC,EAAE,CAAC;AAEL,SAAS,UAAU;IACjB,KAAK,GAAG,CAAC,CAAC;AACZ,CAAC"}
@@ -0,0 +1,2 @@
1
+ export * from './retry.decorator';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./retry.decorator"), exports);
18
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,oDAAkC"}
@@ -0,0 +1,26 @@
1
+ /**
2
+ * retry decorator which is nothing but a high order function wrapper
3
+ *
4
+ * @param options the 'RetryOptions'
5
+ */
6
+ export declare function Retryable(options: RetryOptions): DecoratorFunction;
7
+ export declare class MaxAttemptsError extends Error {
8
+ code: string;
9
+ }
10
+ export interface RetryOptions {
11
+ maxAttempts: number;
12
+ backOffPolicy?: BackOffPolicy;
13
+ backOff?: number;
14
+ doRetry?: (e: any) => boolean;
15
+ value?: ErrorConstructor[];
16
+ exponentialOption?: {
17
+ maxInterval: number;
18
+ multiplier: number;
19
+ };
20
+ }
21
+ export declare enum BackOffPolicy {
22
+ FixedBackOffPolicy = "FixedBackOffPolicy",
23
+ ExponentialBackOffPolicy = "ExponentialBackOffPolicy"
24
+ }
25
+ export declare type DecoratorFunction = (target: Record<string, any>, propertyKey: string, descriptor: TypedPropertyDescriptor<any>) => TypedPropertyDescriptor<any>;
26
+ //# sourceMappingURL=retry.decorator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retry.decorator.d.ts","sourceRoot":"","sources":["../src/retry.decorator.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,OAAO,EAAE,YAAY,GAAG,iBAAiB,CAmElE;AAED,qBAAa,gBAAiB,SAAQ,KAAK;IACzC,IAAI,SAAS;CAMd;AAED,MAAM,WAAW,YAAY;IAC3B,WAAW,EAAE,MAAM,CAAC;IACpB,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,CAAC,CAAC,EAAE,GAAG,KAAK,OAAO,CAAC;IAC9B,KAAK,CAAC,EAAE,gBAAgB,EAAE,CAAC;IAC3B,iBAAiB,CAAC,EAAE;QAAE,WAAW,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KAAE,CAAC;CACjE;AAED,oBAAY,aAAa;IACvB,kBAAkB,uBAAuB;IACzC,wBAAwB,6BAA6B;CACtD;AAED,oBAAY,iBAAiB,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,WAAW,EAAE,MAAM,EAAE,UAAU,EAAE,uBAAuB,CAAC,GAAG,CAAC,KAAK,uBAAuB,CAAC,GAAG,CAAC,CAAC"}
@@ -0,0 +1,106 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.BackOffPolicy = exports.MaxAttemptsError = exports.Retryable = void 0;
13
+ const utils_1 = require("./utils");
14
+ /**
15
+ * retry decorator which is nothing but a high order function wrapper
16
+ *
17
+ * @param options the 'RetryOptions'
18
+ */
19
+ function Retryable(options) {
20
+ /**
21
+ * target: The prototype of the class (Object)
22
+ * propertyKey: The name of the method (string | symbol).
23
+ * descriptor: A TypedPropertyDescriptor — see the type, leveraging the Object.defineProperty under the hood.
24
+ *
25
+ * NOTE: It's very important here we do not use arrow function otherwise 'this' will be messed up due
26
+ * to the nature how arrow function defines this inside.
27
+ *
28
+ */
29
+ return function (target, propertyKey, descriptor) {
30
+ const originalFn = descriptor.value;
31
+ // set default value for ExponentialBackOffPolicy
32
+ if (options.backOffPolicy === BackOffPolicy.ExponentialBackOffPolicy) {
33
+ setExponentialBackOffPolicyDefault();
34
+ }
35
+ descriptor.value = function (...args) {
36
+ return __awaiter(this, void 0, void 0, function* () {
37
+ try {
38
+ return yield retryAsync.apply(this, [originalFn, args, options.maxAttempts, options.backOff]);
39
+ }
40
+ catch (e) {
41
+ if (e instanceof MaxAttemptsError) {
42
+ const msgPrefix = `Failed for '${propertyKey}' for ${options.maxAttempts} times.`;
43
+ e.message = e.message ? `${msgPrefix} Original Error: ${e.message}` : msgPrefix;
44
+ }
45
+ throw e;
46
+ }
47
+ });
48
+ };
49
+ return descriptor;
50
+ };
51
+ function retryAsync(fn, args, maxAttempts, backOff) {
52
+ return __awaiter(this, void 0, void 0, function* () {
53
+ try {
54
+ return yield fn.apply(this, args);
55
+ }
56
+ catch (e) {
57
+ if (--maxAttempts < 0) {
58
+ (e === null || e === void 0 ? void 0 : e.message) && console.error(e.message);
59
+ throw new MaxAttemptsError(e === null || e === void 0 ? void 0 : e.message);
60
+ }
61
+ if (!canRetry(e)) {
62
+ throw e;
63
+ }
64
+ backOff && (yield (0, utils_1.sleep)(backOff));
65
+ if (options.backOffPolicy === BackOffPolicy.ExponentialBackOffPolicy) {
66
+ const newBackOff = backOff * options.exponentialOption.multiplier;
67
+ backOff = newBackOff > options.exponentialOption.maxInterval ? options.exponentialOption.maxInterval : newBackOff;
68
+ }
69
+ return retryAsync.apply(this, [fn, args, maxAttempts, backOff]);
70
+ }
71
+ });
72
+ }
73
+ function canRetry(e) {
74
+ var _a;
75
+ if (options.doRetry && !options.doRetry(e)) {
76
+ return false;
77
+ }
78
+ if (((_a = options.value) === null || _a === void 0 ? void 0 : _a.length) && !options.value.some(errorType => e instanceof errorType)) {
79
+ return false;
80
+ }
81
+ return true;
82
+ }
83
+ function setExponentialBackOffPolicyDefault() {
84
+ !options.backOff && (options.backOff = 1000);
85
+ options.exponentialOption = Object.assign({ maxInterval: 2000, multiplier: 2 }, options.exponentialOption);
86
+ }
87
+ }
88
+ exports.Retryable = Retryable;
89
+ class MaxAttemptsError extends Error {
90
+ constructor() {
91
+ super(...arguments);
92
+ this.code = '429';
93
+ /* if target is ES5, need the 'new.target.prototype'
94
+ constructor(msg?: string) {
95
+ super(msg)
96
+ Object.setPrototypeOf(this, new.target.prototype)
97
+ } */
98
+ }
99
+ }
100
+ exports.MaxAttemptsError = MaxAttemptsError;
101
+ var BackOffPolicy;
102
+ (function (BackOffPolicy) {
103
+ BackOffPolicy["FixedBackOffPolicy"] = "FixedBackOffPolicy";
104
+ BackOffPolicy["ExponentialBackOffPolicy"] = "ExponentialBackOffPolicy";
105
+ })(BackOffPolicy = exports.BackOffPolicy || (exports.BackOffPolicy = {}));
106
+ //# sourceMappingURL=retry.decorator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retry.decorator.js","sourceRoot":"","sources":["../src/retry.decorator.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,mCAAgC;AAEhC;;;;GAIG;AACH,SAAgB,SAAS,CAAC,OAAqB;IAC7C;;;;;;;;OAQG;IACH,OAAO,UAAS,MAA2B,EAAE,WAAmB,EAAE,UAA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,GAAG,KAAK,CAAC;QACb;;;;cAIM;IACR,CAAC;CAAA;AAPD,4CAOC;AAWD,IAAY,aAGX;AAHD,WAAY,aAAa;IACvB,0DAAyC,CAAA;IACzC,sEAAqD,CAAA;AACvD,CAAC,EAHW,aAAa,GAAb,qBAAa,KAAb,qBAAa,QAGxB"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=retry.decorator.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retry.decorator.test.d.ts","sourceRoot":"","sources":["../src/retry.decorator.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,180 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
12
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
13
+ return new (P || (P = Promise))(function (resolve, reject) {
14
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
15
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
16
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
17
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
18
+ });
19
+ };
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ const retry_decorator_1 = require("./retry.decorator");
22
+ class TestClass {
23
+ constructor() {
24
+ this.count = 0;
25
+ }
26
+ testMethod() {
27
+ return __awaiter(this, void 0, void 0, function* () {
28
+ console.log(`test method is called for ${++this.count} time`);
29
+ yield this.called();
30
+ });
31
+ }
32
+ testMethodWithException() {
33
+ return __awaiter(this, void 0, void 0, function* () {
34
+ console.log(`test method is called for ${++this.count} time`);
35
+ yield this.called();
36
+ });
37
+ }
38
+ testDoRetry() {
39
+ return __awaiter(this, void 0, void 0, function* () {
40
+ console.info(`Calling doRetry for the ${++this.count} time at ${new Date().toLocaleTimeString()}`);
41
+ yield this.called();
42
+ });
43
+ }
44
+ fixedBackOffRetry() {
45
+ return __awaiter(this, void 0, void 0, function* () {
46
+ console.info(`Calling fixedBackOffRetry 1s for the ${++this.count} time at ${new Date().toLocaleTimeString()}`);
47
+ yield this.called();
48
+ });
49
+ }
50
+ exponentialBackOffRetry() {
51
+ return __awaiter(this, void 0, void 0, function* () {
52
+ console.info(`Calling ExponentialBackOffRetry backOff 1s, multiplier=3 for the ${++this.count} time at ${new Date().toLocaleTimeString()}`);
53
+ yield this.called();
54
+ });
55
+ }
56
+ called() {
57
+ return __awaiter(this, void 0, void 0, function* () {
58
+ return 'from real implementation';
59
+ });
60
+ }
61
+ }
62
+ __decorate([
63
+ (0, retry_decorator_1.Retryable)({ maxAttempts: 2 }),
64
+ __metadata("design:type", Function),
65
+ __metadata("design:paramtypes", []),
66
+ __metadata("design:returntype", Promise)
67
+ ], TestClass.prototype, "testMethod", null);
68
+ __decorate([
69
+ (0, retry_decorator_1.Retryable)({ maxAttempts: 2, value: [SyntaxError, ReferenceError] }),
70
+ __metadata("design:type", Function),
71
+ __metadata("design:paramtypes", []),
72
+ __metadata("design:returntype", Promise)
73
+ ], TestClass.prototype, "testMethodWithException", null);
74
+ __decorate([
75
+ (0, retry_decorator_1.Retryable)({
76
+ maxAttempts: 3,
77
+ doRetry: (e) => {
78
+ return e.message === 'Error: 429';
79
+ },
80
+ }),
81
+ __metadata("design:type", Function),
82
+ __metadata("design:paramtypes", []),
83
+ __metadata("design:returntype", Promise)
84
+ ], TestClass.prototype, "testDoRetry", null);
85
+ __decorate([
86
+ (0, retry_decorator_1.Retryable)({
87
+ maxAttempts: 3,
88
+ backOffPolicy: retry_decorator_1.BackOffPolicy.FixedBackOffPolicy,
89
+ backOff: 1000,
90
+ }),
91
+ __metadata("design:type", Function),
92
+ __metadata("design:paramtypes", []),
93
+ __metadata("design:returntype", Promise)
94
+ ], TestClass.prototype, "fixedBackOffRetry", null);
95
+ __decorate([
96
+ (0, retry_decorator_1.Retryable)({
97
+ maxAttempts: 3,
98
+ backOffPolicy: retry_decorator_1.BackOffPolicy.ExponentialBackOffPolicy,
99
+ exponentialOption: { maxInterval: 4000, multiplier: 3 },
100
+ }),
101
+ __metadata("design:type", Function),
102
+ __metadata("design:paramtypes", []),
103
+ __metadata("design:returntype", Promise)
104
+ ], TestClass.prototype, "exponentialBackOffRetry", null);
105
+ describe('Retry Test', () => {
106
+ let testClass;
107
+ beforeEach(() => {
108
+ testClass = new TestClass();
109
+ });
110
+ test('normal retry', () => __awaiter(void 0, void 0, void 0, function* () {
111
+ const calledSpy = jest.spyOn(testClass, 'called');
112
+ calledSpy.mockRejectedValueOnce(new Error('rejected'));
113
+ calledSpy.mockResolvedValueOnce('fulfilled');
114
+ yield testClass.testMethod();
115
+ expect(calledSpy).toHaveBeenCalledTimes(2);
116
+ }));
117
+ test('exceed max retry', () => __awaiter(void 0, void 0, void 0, function* () {
118
+ const calledSpy = jest.spyOn(testClass, 'called');
119
+ const errorMsg = 'rejected';
120
+ calledSpy.mockRejectedValue(new Error(errorMsg));
121
+ try {
122
+ yield testClass.testMethod();
123
+ }
124
+ catch (e) {
125
+ expect(e).not.toBeUndefined();
126
+ expect(e.message.includes(errorMsg));
127
+ }
128
+ expect(calledSpy).toHaveBeenCalledTimes(3);
129
+ }));
130
+ test('retry with specific error', () => __awaiter(void 0, void 0, void 0, function* () {
131
+ const calledSpy = jest.spyOn(testClass, 'called');
132
+ calledSpy.mockImplementationOnce(() => { throw new SyntaxError('I failed!'); });
133
+ yield testClass.testMethodWithException();
134
+ expect(calledSpy).toHaveBeenCalledTimes(2);
135
+ }));
136
+ test('retry with specific error not match', () => __awaiter(void 0, void 0, void 0, function* () {
137
+ const calledSpy = jest.spyOn(testClass, 'called');
138
+ calledSpy.mockImplementationOnce(() => { throw new Error('I failed!'); });
139
+ try {
140
+ yield testClass.testMethodWithException();
141
+ }
142
+ catch (e) { }
143
+ expect(calledSpy).toHaveBeenCalledTimes(1);
144
+ }));
145
+ test('do retry when high order function retry true', () => __awaiter(void 0, void 0, void 0, function* () {
146
+ const calledSpy = jest.spyOn(testClass, 'called');
147
+ calledSpy.mockImplementationOnce(() => { throw new Error('Error: 429'); });
148
+ yield testClass.testDoRetry();
149
+ expect(calledSpy).toHaveBeenCalledTimes(2);
150
+ }));
151
+ test('do NOT retry when high order function retry false', () => __awaiter(void 0, void 0, void 0, function* () {
152
+ const calledSpy = jest.spyOn(testClass, 'called');
153
+ calledSpy.mockImplementationOnce(() => { throw new Error('Error: 500'); });
154
+ try {
155
+ yield testClass.testDoRetry();
156
+ }
157
+ catch (e) { }
158
+ expect(calledSpy).toHaveBeenCalledTimes(1);
159
+ }));
160
+ test('fix backOff policy', () => __awaiter(void 0, void 0, void 0, function* () {
161
+ const calledSpy = jest.spyOn(testClass, 'called');
162
+ calledSpy.mockImplementation(() => { throw new Error('Error: 500'); });
163
+ try {
164
+ yield testClass.fixedBackOffRetry();
165
+ }
166
+ catch (e) { }
167
+ expect(calledSpy).toHaveBeenCalledTimes(4);
168
+ }));
169
+ test('exponential backOff policy', () => __awaiter(void 0, void 0, void 0, function* () {
170
+ jest.setTimeout(60000);
171
+ const calledSpy = jest.spyOn(testClass, 'called');
172
+ calledSpy.mockImplementation(() => { throw new Error(); });
173
+ try {
174
+ yield testClass.exponentialBackOffRetry();
175
+ }
176
+ catch (e) { }
177
+ expect(calledSpy).toHaveBeenCalledTimes(4);
178
+ }));
179
+ });
180
+ //# sourceMappingURL=retry.decorator.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retry.decorator.test.js","sourceRoot":"","sources":["../src/retry.decorator.test.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,uDAA6D;AAE7D,MAAM,SAAS;IAEb;QACE,IAAI,CAAC,KAAK,GAAG,CAAC,CAAC;IACjB,CAAC;IAEK,UAAU;;YACd,OAAO,CAAC,GAAG,CAAC,6BAA6B,EAAE,IAAI,CAAC,KAAK,OAAO,CAAC,CAAC;YAC9D,MAAM,IAAI,CAAC,MAAM,EAAE,CAAC;QACtB,CAAC;KAAA;IAGK,uBAAuB;;YAC3B,OAAO,CAAC,GAAG,CAAC,6BAA6B,EAAE,IAAI,CAAC,KAAK,OAAO,CAAC,CAAC;YAC9D,MAAM,IAAI,CAAC,MAAM,EAAE,CAAC;QACtB,CAAC;KAAA;IAQK,WAAW;;YACf,OAAO,CAAC,IAAI,CAAC,2BAA2B,EAAE,IAAI,CAAC,KAAK,YAAY,IAAI,IAAI,EAAE,CAAC,kBAAkB,EAAE,EAAE,CAAC,CAAC;YACnG,MAAM,IAAI,CAAC,MAAM,EAAE,CAAC;QACtB,CAAC;KAAA;IAOK,iBAAiB;;YACrB,OAAO,CAAC,IAAI,CAAC,wCAAwC,EAAE,IAAI,CAAC,KAAK,YAAY,IAAI,IAAI,EAAE,CAAC,kBAAkB,EAAE,EAAE,CAAC,CAAC;YAChH,MAAM,IAAI,CAAC,MAAM,EAAE,CAAC;QACtB,CAAC;KAAA;IAOK,uBAAuB;;YAC3B,OAAO,CAAC,IAAI,CAAC,oEAAoE,EAAE,IAAI,CAAC,KAAK,YAAY,IAAI,IAAI,EAAE,CAAC,kBAAkB,EAAE,EAAE,CAAC,CAAC;YAC5I,MAAM,IAAI,CAAC,MAAM,EAAE,CAAC;QACtB,CAAC;KAAA;IAEK,MAAM;;YACV,OAAO,0BAA0B,CAAC;QACpC,CAAC;KAAA;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CAAC,CAAC,CAAC,CAAC;QACvE,IAAI;YACF,MAAM,SAAS,CAAC,iBAAiB,EAAE,CAAC;SACrC;QAAC,OAAO,CAAC,EAAE,GAAE;QACd,MAAM,CAAC,SAAS,CAAC,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAAC;IAC7C,CAAC,CAAA,CAAC,CAAC;IAEH,IAAI,CAAC,4BAA4B,EAAE,GAAS,EAAE;QAC5C,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;QACvB,MAAM,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;QAClD,SAAS,CAAC,kBAAkB,CAAC,GAAG,EAAE,GAAG,MAAM,IAAI,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QAC3D,IAAI;YACF,MAAM,SAAS,CAAC,uBAAuB,EAAE,CAAC;SAC3C;QAAC,OAAO,CAAC,EAAE,GAAE;QACd,MAAM,CAAC,SAAS,CAAC,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAAC;IAC7C,CAAC,CAAA,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
@@ -0,0 +1,2 @@
1
+ export declare const sleep: (ms?: number) => void;
2
+ //# sourceMappingURL=utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,KAAK,EAAE,CAAC,EAAE,CAAC,EAAE,MAAM,KAAK,IAAuE,CAAC"}
package/dist/utils.js ADDED
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sleep = void 0;
4
+ // wrap the native setTimeout with Promise so it can be used with `await`.
5
+ const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
6
+ exports.sleep = sleep;
7
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;AAAA,0EAA0E;AACnE,MAAM,KAAK,GAA0B,CAAC,EAAW,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;AAAhG,QAAA,KAAK,SAA2F"}
package/jest.config.js CHANGED
@@ -13,4 +13,5 @@ module.exports = {
13
13
  collectCoverage: true,
14
14
  'coverageReporters': ['json', 'html'],
15
15
  verbose: true,
16
+ testTimeout: 30000,
16
17
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typescript-retry-decorator",
3
- "version": "2.0.0",
3
+ "version": "2.0.5",
4
4
  "description": "A simple retry decorator for typescript with no dependency.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -9,7 +9,7 @@
9
9
  "test": "jest",
10
10
  "example": "ts-node src/example.ts",
11
11
  "lint": "eslint --ext .ts src/",
12
- "build": "tsc -d -p ."
12
+ "build": "tsc --declaration --project ."
13
13
  },
14
14
  "repository": {
15
15
  "type": "git",
@@ -27,15 +27,15 @@
27
27
  },
28
28
  "homepage": "https://github.com/vcfvct/typescript-retry-decorator#readme",
29
29
  "devDependencies": {
30
- "@types/jest": "^26.0.20",
31
- "@types/node": "^14.14.6",
32
- "@typescript-eslint/eslint-plugin": "^2.10.0",
33
- "@typescript-eslint/parser": "^2.10.0",
34
- "eslint": "^6.7.2",
30
+ "@types/jest": "^28.1.1",
31
+ "@types/node": "^17.0.41",
32
+ "@typescript-eslint/eslint-plugin": "^5.27.1",
33
+ "@typescript-eslint/parser": "^5.27.1",
34
+ "eslint": "^8.17.0",
35
35
  "eslint-config-ts-vcfvct": "^1.0.0",
36
- "jest": "^26.6.3",
37
- "ts-jest": "^26.4.4",
38
- "ts-node": "^9.0.0",
39
- "typescript": "^4.0.0"
36
+ "jest": "^28.1.1",
37
+ "ts-jest": "^28.0.4",
38
+ "ts-node": "^10.8.1",
39
+ "typescript": "^4.7.3"
40
40
  }
41
41
  }
package/src/index.ts CHANGED
@@ -1 +1 @@
1
- export { Retryable, RetryOptions, BackOffPolicy } from './retry.decorator';
1
+ export * from './retry.decorator';
@@ -5,7 +5,7 @@ import { sleep } from './utils';
5
5
  *
6
6
  * @param options the 'RetryOptions'
7
7
  */
8
- export function Retryable(options: RetryOptions): Function {
8
+ export function Retryable(options: RetryOptions): DecoratorFunction {
9
9
  /**
10
10
  * target: The prototype of the class (Object)
11
11
  * propertyKey: The name of the method (string | symbol).
@@ -16,7 +16,7 @@ export function Retryable(options: RetryOptions): Function {
16
16
  *
17
17
  */
18
18
  return function(target: Record<string, any>, propertyKey: string, descriptor: TypedPropertyDescriptor<any>) {
19
- const originalFn: Function = descriptor.value;
19
+ const originalFn = descriptor.value;
20
20
  // set default value for ExponentialBackOffPolicy
21
21
  if (options.backOffPolicy === BackOffPolicy.ExponentialBackOffPolicy) {
22
22
  setExponentialBackOffPolicyDefault();
@@ -35,7 +35,7 @@ export function Retryable(options: RetryOptions): Function {
35
35
  return descriptor;
36
36
  };
37
37
 
38
- async function retryAsync(fn: Function, args: any[], maxAttempts: number, backOff?: number): Promise<any> {
38
+ async function retryAsync(fn: () => any, args: any[], maxAttempts: number, backOff?: number): Promise<any> {
39
39
  try {
40
40
  return await fn.apply(this, args);
41
41
  } catch (e) {
@@ -75,7 +75,7 @@ export function Retryable(options: RetryOptions): Function {
75
75
  }
76
76
 
77
77
  export class MaxAttemptsError extends Error {
78
- code = '429'
78
+ code = '429';
79
79
  /* if target is ES5, need the 'new.target.prototype'
80
80
  constructor(msg?: string) {
81
81
  super(msg)
@@ -97,3 +97,5 @@ export enum BackOffPolicy {
97
97
  ExponentialBackOffPolicy = 'ExponentialBackOffPolicy'
98
98
  }
99
99
 
100
+ export type DecoratorFunction = (target: Record<string, any>, propertyKey: string, descriptor: TypedPropertyDescriptor<any>) => TypedPropertyDescriptor<any>;
101
+
package/src/utils.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  // wrap the native setTimeout with Promise so it can be used with `await`.
2
- export const sleep: Function = (ms?: number) => new Promise(resolve => setTimeout(resolve, ms));
2
+ export const sleep: (ms?: number) => void = (ms?: number) => new Promise(resolve => setTimeout(resolve, ms));
package/tsconfig.json CHANGED
@@ -8,6 +8,7 @@
8
8
  "emitDecoratorMetadata": true,
9
9
  "experimentalDecorators": true,
10
10
  "sourceMap": true,
11
+ "declarationMap": true,
11
12
  "skipLibCheck": true,
12
13
  "lib": [
13
14
  "es2017",
@@ -28,4 +29,4 @@
28
29
  "node_modules",
29
30
  "dist",
30
31
  ]
31
- }
32
+ }