Skip to content

Commit

Permalink
feat: Add support for conditional jobs declaration
Browse files Browse the repository at this point in the history
By ignoring falsy values in the jobs array.
  • Loading branch information
franky47 committed Jan 20, 2022
1 parent 85544a4 commit 28a5372
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 2 deletions.
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
17 changes: 17 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
})
})
8 changes: 6 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Config> = async function fastifyCronPlugin(
Expand Down Expand Up @@ -66,7 +68,9 @@ const plugin: FastifyPluginAsync<Config> = async function fastifyCronPlugin(
}
}
for (const params of opts.jobs || []) {
decorator.createJob(params)
if (params) {
decorator.createJob(params)
}
}

server.decorate('cron', decorator)
Expand Down

0 comments on commit 28a5372

Please sign in to comment.