Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: implement CronJon type generics #1538

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 12 additions & 6 deletions lib/scheduler.registry.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import { Injectable, Logger } from '@nestjs/common';
import { CronJob } from 'cron';
import type { CronJob, CronOnCompleteCommand } from 'cron';
import { DUPLICATE_SCHEDULER, NO_SCHEDULER_FOUND } from './schedule.messages';

@Injectable()
export class SchedulerRegistry {
export class SchedulerRegistry<
OC extends CronOnCompleteCommand | null = null,
C = null,
> {
private readonly logger = new Logger(SchedulerRegistry.name);

private readonly cronJobs = new Map<string, CronJob>();
private readonly cronJobs = new Map<string, CronJob<OC, C>>();
private readonly timeouts = new Map<string, any>();
private readonly intervals = new Map<string, any>();

Expand Down Expand Up @@ -47,7 +50,7 @@ export class SchedulerRegistry {
return ref;
}

addCronJob(name: string, job: CronJob) {
addCronJob(name: string, job: CronJob<OC, C>) {
const ref = this.cronJobs.get(name);
if (ref) {
throw new Error(DUPLICATE_SCHEDULER('Cron Job', name));
Expand All @@ -73,7 +76,7 @@ export class SchedulerRegistry {
this.timeouts.set(name, timeoutId);
}

getCronJobs(): Map<string, CronJob> {
getCronJobs(): Map<string, CronJob<OC, C>> {
return this.cronJobs;
}

Expand Down Expand Up @@ -103,7 +106,10 @@ export class SchedulerRegistry {
this.timeouts.delete(name);
}

private wrapFunctionInTryCatchBlocks(methodRef: Function, instance: object): (...args: unknown[]) => Promise<void> {
private wrapFunctionInTryCatchBlocks(
methodRef: Function,
instance: object,
): (...args: unknown[]) => Promise<void> {
return async (...args: unknown[]) => {
try {
await methodRef.call(instance, ...args);
Expand Down
18 changes: 10 additions & 8 deletions tests/e2e/cron-jobs.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { INestApplication, Logger } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import { CronJob } from "cron";
import { CronJob } from 'cron';
import sinon from 'sinon';
import { CronExpression } from "../../lib";
import { CronExpression } from '../../lib';
Copy link
Author

@nerdstep nerdstep Jan 5, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please excuse the excess formatting changes, prettier wanted to do its thing...

import { SchedulerRegistry } from '../../lib/scheduler.registry';
import { AppModule } from '../src/app.module';
import { CronService } from '../src/cron.service';
Expand Down Expand Up @@ -41,24 +41,26 @@ describe('Cron', () => {
expect(service.callsCount).toEqual(3);
});

it(`should catch and log exception inside cron-function added by scheduler`, async() => {
it(`should catch and log exception inside cron-function added by scheduler`, async () => {
await app.init();
const registry = app.get(SchedulerRegistry);
const registry = app.get<SchedulerRegistry>(SchedulerRegistry);
registry['logger'].error = jest.fn();
const job = new CronJob(CronExpression.EVERY_SECOND, () => {
throw new Error('ERROR IN CRONJOB GOT CATCHED');
});
registry.addCronJob('THROWS_EXCEPTION_INSIDE', job);
job.start();
clock.tick('1');
expect(registry['logger'].error).toHaveBeenCalledWith(new Error('ERROR IN CRONJOB GOT CATCHED'));
expect(registry['logger'].error).toHaveBeenCalledWith(
new Error('ERROR IN CRONJOB GOT CATCHED'),
);
});

it(`should run "cron" once after 30 seconds`, async () => {
const service = app.get(CronService);

await app.init();
const registry = app.get(SchedulerRegistry);
const registry = app.get<SchedulerRegistry>(SchedulerRegistry);
const job = registry.getCronJob('EXECUTES_EVERY_30_SECONDS');
deleteAllRegisteredJobsExceptOne(registry, 'EXECUTES_EVERY_30_SECONDS');

Expand All @@ -79,7 +81,7 @@ describe('Cron', () => {
await app.init();
expect(service.callsCount).toEqual(0);

const registry = app.get(SchedulerRegistry);
const registry = app.get<SchedulerRegistry>(SchedulerRegistry);
const job = registry.getCronJob('EXECUTES_EVERY_MINUTE');
deleteAllRegisteredJobsExceptOne(registry, 'EXECUTES_EVERY_MINUTE');

Expand All @@ -97,7 +99,7 @@ describe('Cron', () => {
await app.init();
expect(service.callsCount).toEqual(0);

const registry = app.get(SchedulerRegistry);
const registry = app.get<SchedulerRegistry>(SchedulerRegistry);
const job = registry.getCronJob('EXECUTES_EVERY_HOUR');
deleteAllRegisteredJobsExceptOne(registry, 'EXECUTES_EVERY_HOUR');

Expand Down