node-cron.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { _optionalChain } from '@sentry/utils';
  2. import { withMonitor } from '@sentry/core';
  3. import { replaceCronNames } from './common.js';
  4. /**
  5. * Wraps the `node-cron` library with check-in monitoring.
  6. *
  7. * ```ts
  8. * import * as Sentry from "@sentry/node";
  9. * import cron from "node-cron";
  10. *
  11. * const cronWithCheckIn = Sentry.cron.instrumentNodeCron(cron);
  12. *
  13. * cronWithCheckIn.schedule(
  14. * "* * * * *",
  15. * () => {
  16. * console.log("running a task every minute");
  17. * },
  18. * { name: "my-cron-job" },
  19. * );
  20. * ```
  21. */
  22. function instrumentNodeCron(lib) {
  23. return new Proxy(lib, {
  24. get(target, prop) {
  25. if (prop === 'schedule' && target.schedule) {
  26. // When 'get' is called for schedule, return a proxied version of the schedule function
  27. return new Proxy(target.schedule, {
  28. apply(target, thisArg, argArray) {
  29. const [expression, , options] = argArray;
  30. if (!_optionalChain([options, 'optionalAccess', _ => _.name])) {
  31. throw new Error('Missing "name" for scheduled job. A name is required for Sentry check-in monitoring.');
  32. }
  33. return withMonitor(
  34. options.name,
  35. () => {
  36. return target.apply(thisArg, argArray);
  37. },
  38. {
  39. schedule: { type: 'crontab', value: replaceCronNames(expression) },
  40. timezone: _optionalChain([options, 'optionalAccess', _2 => _2.timezone]),
  41. },
  42. );
  43. },
  44. });
  45. } else {
  46. return target[prop];
  47. }
  48. },
  49. });
  50. }
  51. export { instrumentNodeCron };
  52. //# sourceMappingURL=node-cron.js.map