Skip to content

Commit

Permalink
feat: add isCronTimeValid function to validate cron expressions
Browse files Browse the repository at this point in the history
  • Loading branch information
WillianAgostini committed Feb 19, 2025
1 parent 9159759 commit c770c73
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 9 deletions.
10 changes: 2 additions & 8 deletions examples/is_crontime_valid.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,3 @@
import { CronJob } from '../src';
import { isCronTimeValid } from '../src';

try {
new CronJob('NOT VALID', () => {
console.log("shouldn't get printed");
});
} catch (e) {
console.log('omg err', e);
}
console.log('is valid? ', isCronTimeValid('NOT VALID'));
11 changes: 11 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,14 @@ export const sendAt = (cronTime: string | Date | DateTime): DateTime =>

export const timeout = (cronTime: string | Date | DateTime): number =>
new CronTime(cronTime).getTimeout();

export const isCronTimeValid = (
cronTime: string | Date | DateTime
): boolean => {
try {
new CronTime(cronTime);
return true;
} catch (_) {
return false;
}
};
18 changes: 17 additions & 1 deletion tests/crontime.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { DateTime } from 'luxon';
import sinon from 'sinon';
import { CronTime } from '../src';
import { CronTime, isCronTimeValid } from '../src';

describe('crontime', () => {
// eslint-disable-next-line jest/no-standalone-expect
Expand Down Expand Up @@ -778,3 +778,19 @@ describe('crontime', () => {
}).toThrow();
});
});

describe('isCronTimeValid', () => {
it('should return true for valid cron expressions', () => {
expect(isCronTimeValid('* * * * *')).toBe(true);
expect(isCronTimeValid('0 0 * * *')).toBe(true);
expect(isCronTimeValid('0 0 1 1 *')).toBe(true);
expect(isCronTimeValid('*/5 * * * *')).toBe(true);
});

it('should return false for invalid cron expressions', () => {
expect(isCronTimeValid('* * * *')).toBe(false);
expect(isCronTimeValid('60 * * * *')).toBe(false);
expect(isCronTimeValid('* * * * * * *')).toBe(false);
expect(isCronTimeValid('invalid cron')).toBe(false);
});
});

0 comments on commit c770c73

Please sign in to comment.