In my current project, I am developing a custom cron decorator that not only schedules tasks but also logs the name of the task when it is executed. To accomplish this, I have merged the default nestjs scheduling Cron decorator with a unique LogTask decorator in the code snippet below:
//cron-with-log.decorator.ts
const CronWithLog = (
taskName: string,
cronTime: string | Date,
options?: CronOptions,
) => {
return applyDecorators(LogTask(taskName), Cron(cronTime, options));
};
export default CronWithLog;
//log-task.decorator.ts
const LogTask = (taskName) => {
return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
const targetFunc = descriptor.value;
const logger = new Logger('Scheduler');
descriptor.value = (...args: any[]) => {
logger.log(`Executing Task: ${taskName}`);
targetFunc.apply(this, args);
};
return descriptor;
};
};
export default LogTask;
Now, let me show you how I implement this solution:
@Injectable()
export class Task {
constructor(
private readonly taskService: TaskService,
) {}
@CronWithLog('Example Task', '* * * * * *')
async run() {
console.log(taskService.get(1))
}
}
The logging functionality works perfectly as intended:
[Nest] 98 - 02/12/2021, 7:36:07 AM [Scheduler] Executing Task: Example Task
However, I encountered an issue where the TaskService
dependency is not being initialized, causing the task to fail. Upon further investigation, changing the order of decorators within the applyDecorators
function from
applyDecorators(LogTask(taskName), Cron(cronTime, options))
to applyDecorators(Cron(cronTime, options), LogTask(taskName))
resulted in both the logging and task execution failing altogether. Interestingly, running the job using the default Cron decorator works without any issues.
Is there something crucial that I am overlooking to ensure proper initialization of dependencies within my LogTask function?