-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
65 lines (54 loc) · 1.47 KB
/
index.js
File metadata and controls
65 lines (54 loc) · 1.47 KB
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
module.exports = ({collection, handleErr: handleError = () => {}}) => {
let timeoutID;
const fns = {};
async function updateTimeout() {
const dateDoc = await collection.aggregate([{
$group: {_id: {}, date: {$min: '$date'}}
}]).next();
if (!dateDoc) {
return clearTimeout(timeoutID);
}
const {date} = dateDoc;
clearTimeout(timeoutID);
timeoutID = setTimeout(async () => {
try {
const {value: job} = await collection.findOneAndDelete({date});
if (!job) {
return;
}
const {name, data} = job;
const fn = fns[name];
if (!fn) {
throw new Error(`Unknown job ${name}`);
}
(async () => fn(data))().catch(handleError);
} catch (error) {
handleError(error);
} finally {
updateTimeout().catch(handleError);
}
}, date - Date.now());
}
return {
async start() {
await collection.createIndex({date: 1});
await updateTimeout();
},
define(name, callback) {
fns[name] = callback;
},
async addJob({date, name, data}) {
date = new Date(date);
if (Number.isNaN(date.getTime())) {
throw new TypeError('Invalid date');
}
await collection.insertOne({date, name, data});
await updateTimeout();
},
async delJob(search) {
const {deletedCount} = await collection.deleteMany(search);
await updateTimeout();
return deletedCount;
}
};
};