-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathnode-schedule.ts
More file actions
69 lines (62 loc) · 2.33 KB
/
Copy pathnode-schedule.ts
File metadata and controls
69 lines (62 loc) · 2.33 KB
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
import { withMonitor } from '@sentry/core';
import { replaceCronNames } from './common';
export interface NodeSchedule {
scheduleJob(
nameOrExpression: string | Date | object,
expressionOrCallback: string | Date | object | (() => void),
callback?: () => void,
): unknown;
}
/**
* Instruments the `node-schedule` library to send a check-in event to Sentry for each job execution.
*
* ```ts
* import * as Sentry from '@sentry/node';
* import * as schedule from 'node-schedule';
*
* const scheduleWithCheckIn = Sentry.cron.instrumentNodeSchedule(schedule);
*
* const job = scheduleWithCheckIn.scheduleJob('my-cron-job', '* * * * *', () => {
* console.log('You will see this message every minute');
* });
* ```
*/
export function instrumentNodeSchedule<T>(lib: T & NodeSchedule): T {
return new Proxy(lib, {
get(target, prop: keyof NodeSchedule) {
if (prop === 'scheduleJob') {
// eslint-disable-next-line @typescript-eslint/unbound-method
return new Proxy(target.scheduleJob, {
apply(target, thisArg, argArray: Parameters<NodeSchedule['scheduleJob']>) {
const [nameOrExpression, expressionOrCallback, callback] = argArray;
if (
typeof nameOrExpression !== 'string' ||
typeof expressionOrCallback !== 'string' ||
typeof callback !== 'function'
) {
throw new Error(
"Automatic instrumentation of 'node-schedule' requires the first parameter of 'scheduleJob' to be a job name string and the second parameter to be a crontab string",
);
}
const monitorSlug = nameOrExpression;
const expression = expressionOrCallback;
async function monitoredCallback(): Promise<void> {
return withMonitor(
monitorSlug,
async () => {
// oxlint-disable-next-line typescript/await-thenable -- callback may be async at runtime
await callback?.();
},
{
schedule: { type: 'crontab', value: replaceCronNames(expression) },
},
);
}
return target.apply(thisArg, [monitorSlug, expression, monitoredCallback]);
},
});
}
return target[prop];
},
});
}