blob: 7983c292799a35c8bb607d68e5824b376c3fa128 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
# mongo-cronjob
Cron-based job scheduler which persists events to MongoDB
## Installation
```
npm i mongo-cronjob
```
## Usage example
```js
const mongoose = require('mongoose');
const { Client, Scheduler } = require('mongo-cronjob');
// Initialize client with existing connection
const client = new Client(mongoose.connection);
const EventModel = client.Event;
const LogModel = client.Log;
// Initialize scheduler
const scheduler = new Scheduler(EventModel);
scheduler.registerHandler('test', async event => {
// Your complicated async logic goes here instead
const { message } = event.context;
event.log(message);
});
EventModel.create({
type: 'test', // Matches handler type
schedule: '*/30 * * * * *', // Every 30 seconds
context: {
message: 'Hello, world!'
}
});
```
## API
### Log
Document interface:
```ts
interface LogDocument extends Document {
eventId: string;
message: string;
}
```
### Event
Document interface:
```ts
interface EventDocument<Context = any> extends Document {
type: string; // Scheduler will try to find a handler for this type
schedule: string; // Should be a valid crontab
status?: 'notStarted' | 'running' | 'complete' | 'failed';
error?: string; // Latest error thrown by handler
context: Context;
nextRunAt?: Date; // Updated on 'save' hook (based on schedule)
lastRunAt?: Date;
}
```
Every field except for `event.context` is managed by `Scheduler` automatically. For logging and managing status (useful in handlers), following methods are available:
- `event.log(message: string): Promise<Log>` - create a `Log` instance and also redirect to console
- `event.fail(error: Error | string): Promise<Event>` - set status to `failed` and log the error nicely
- `event.getLogs(): Promise<Log[]>` - return all logs for this event
|