Skip to content

Commit

Permalink
refactor: ♻️ refactor parameters timeZone & utcOffset
Browse files Browse the repository at this point in the history
refactor runtime check & typings of exclusive parameters timeZone & utcOffset and Add getTimeZoneAndOffset function to utils.ts
  • Loading branch information
Victor1890 committed Jan 23, 2024
1 parent 94e8aac commit 1b33011
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 10 deletions.
16 changes: 6 additions & 10 deletions src/job.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
CronOnCompleteCommand,
WithOnComplete
} from './types/cron.types';
import { getTimeZoneAndOffset } from './utils';

export class CronJob<OC extends CronOnCompleteCommand | null = null, C = null> {
cronTime: CronTime;
Expand Down Expand Up @@ -61,17 +62,12 @@ export class CronJob<OC extends CronOnCompleteCommand | null = null, C = null> {
this.context = (context ?? this) as CronContext<C>;

// runtime check for JS users
if (timeZone != null && utcOffset != null) {
throw new ExclusiveParametersError('timeZone', 'utcOffset');
}
const { timeZone: tz, utcOffset: uo } = getTimeZoneAndOffset(
timeZone,
utcOffset
);

if (timeZone != null) {
this.cronTime = new CronTime(cronTime, timeZone, null);
} else if (utcOffset != null) {
this.cronTime = new CronTime(cronTime, null, utcOffset);
} else {
this.cronTime = new CronTime(cronTime, timeZone, utcOffset);
}
this.cronTime = new CronTime(cronTime, tz, uo as null | undefined);

if (unrefTimeout != null) {
this.unrefTimeout = unrefTimeout;
Expand Down
18 changes: 18 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,25 @@
import { ExclusiveParametersError } from './errors';
import { Ranges } from './types/cron.types';

export const getRecordKeys = <K extends Ranges[keyof Ranges]>(
record: Partial<Record<K, boolean>>
) => {
return Object.keys(record) as unknown as (keyof typeof record)[];
};

export const getTimeZoneAndOffset = (
timeZone?: string | null,
utcOffset?: number | null
) => {
if (timeZone != null && utcOffset != null) {
throw new ExclusiveParametersError('timeZone', 'utcOffset');
}

if (timeZone != null) {
return { timeZone, utcOffset: null };
} else if (utcOffset != null) {
return { timeZone: null, utcOffset };
} else {
return { timeZone: null, utcOffset: null };
}
};

0 comments on commit 1b33011

Please sign in to comment.