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
66
67
68
69
70
71
72
73
74
75
|
const { Types } = require('mongoose');
const Agenda = require('agenda');
const _ = require('lodash');
const { getConnection } = require('../../connectDb.js');
const handleAttendClassJob = require('../../handlers');
class Events {
setup(app) {
this.collectionName = 'events';
// Reuse mongoose connection
const connection = getConnection();
this.agenda = new Agenda();
this.agenda.mongo(
connection.collection(this.collectionName).conn.db,
this.collectionName
);
// Define jobs
this.agenda.define('attend class', handleAttendClassJob);
// Logs
this.agenda.on('start', job => {
console.log(`Starting ${job.attrs.data.name} job`);
job.attrs.status = 'running';
job.save();
});
this.agenda.on('complete', job => {
console.log(`Job ${job.attrs.data.name} finished`);
if (job.attrs.status === 'running') {
job.attrs.status = 'complete';
job.save();
}
});
this.agenda.on('fail', (err, job) => {
console.log(`Job ${job.attrs.data.name} failed with the error ${err.message}`);
job.attrs.status = 'failed';
job.save();
});
return this.agenda.start();
}
create(data, params) {
return this.agenda.schedule(data.date, 'attend class', data);
}
find(params) {
return this.agenda.jobs({});
}
findOneById(id) {
return this.agenda
.jobs({ _id: Types.ObjectId(id) })
.then(results => results[0]);
}
async patch(id, attrs, params) {
console.log(`Patch ${id}`);
const job = await this.findOneById(id);
job.attrs = _.merge(job.attrs, attrs);
return this.agenda.saveJob(job);
}
async remove(id) {
console.log(`Remove ${id}`);
return this.agenda.cancel({ _id: Types.ObjectId(id) });
}
}
module.exports = app => app.use('/events', new Events());
|