-
-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathschedule.wrapper.ts
71 lines (63 loc) · 2.25 KB
/
schedule.wrapper.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { Locker } from './interfaces/locker.interface';
import { Logger } from '@nestjs/common';
import { JOB_EXECUTE_ERROR, RELEASE_LOCK_ERROR, TRY_LOCK_FAILED } from './schedule.messages';
const logger = new Logger('Schedule');
export class ScheduleWrapper {
public async immediately(name: string, target: Promise<Function>) {
(await target).call(null).catch(e => logger.error(JOB_EXECUTE_ERROR(name), e));
return target;
}
public async retryable(retries: number = -1, retry: number = 5000, target: Promise<Function>): Promise<Function> {
let count = 0;
let timer: NodeJS.Timeout;
const targetRef = () => {
return new Promise(async (resolve, reject) => {
const wrapperRef = async () => {
try {
await (await target).call(null);
count = 0;
resolve();
} catch (e) {
if (count < retries) {
if (timer) {
clearTimeout(timer);
}
count++;
timer = setTimeout(() => wrapperRef(), retry);
return;
}
count = 0;
reject(e);
}
};
await wrapperRef();
});
};
return targetRef;
}
public async lockable(name: string, locker: Locker, target: Promise<Function>): Promise<Function> {
if (locker) {
locker.init(name);
try {
const locked = await locker.tryLock();
if (!locked) {
logger.error(TRY_LOCK_FAILED(name));
return;
}
} catch (e) {
logger.error(TRY_LOCK_FAILED(name));
return;
}
}
return async () => {
if (locker) {
try {
locker.release();
} catch (e) {
logger.error(RELEASE_LOCK_ERROR(name));
}
}
await (await target).call(null);
};
}
}