From 28a5372a94c6c6c02177413c82e77c4d390e3f03 Mon Sep 17 00:00:00 2001 From: Francois Best Date: Thu, 20 Jan 2022 22:16:52 +0100 Subject: [PATCH] feat: Add support for conditional jobs declaration By ignoring falsy values in the jobs array. --- README.md | 20 ++++++++++++++++++++ src/index.test.ts | 17 +++++++++++++++++ src/index.ts | 8 ++++++-- 3 files changed, 43 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 3cdb151..39cd51e 100644 --- a/README.md +++ b/README.md @@ -207,6 +207,26 @@ if (process.env.INSTANCE_NUMBER === 0) { } ``` +## Conditionally running jobs + +You may want to run certain jobs in development only, or under other conditions. + +`fastify-cron` will ignore any falsy values in the `jobs` array, so you can do: + +```ts +server.register(fastifyCron, { + jobs: [ + process.env.ENABLE_DEV_JOB === 'true' && { + name: 'devJob', + cronTime: '* * * * *', + onTick: server => { + // ... + } + } + ] +}) +``` + ## Compatibility Notes Some compatibility issues may arise with the [`cron` API](https://github.com/kelektiv/node-cron#api). diff --git a/src/index.test.ts b/src/index.test.ts index 353c0c3..2c38e31 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -112,4 +112,21 @@ describe('Creating jobs manually after registration', () => { expect(job).toBeDefined() expect(job!.running).toBeFalsy() }) + + test('falsy values are ignored in the jobs array', async () => { + const server = Fastify({ logger: false }) + const spy = jest.fn() + await server.register(fastifyCron, { + jobs: [ + false && { + name: 'foo', + cronTime: '* * * * *', + onTick: spy + } + ] + }) + await server.ready() + const job = server.cron.getJobByName('foo') + expect(job).toBeUndefined() + }) }) diff --git a/src/index.ts b/src/index.ts index e8a07ad..f9fa6f9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -27,8 +27,10 @@ export interface CronDecorator { stopAllJobs: () => void } +export type FalsyValue = undefined | null | false + export interface Config { - jobs?: Params[] + jobs?: (Params | FalsyValue)[] } const plugin: FastifyPluginAsync = async function fastifyCronPlugin( @@ -66,7 +68,9 @@ const plugin: FastifyPluginAsync = async function fastifyCronPlugin( } } for (const params of opts.jobs || []) { - decorator.createJob(params) + if (params) { + decorator.createJob(params) + } } server.decorate('cron', decorator)