forked from msavin/queue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.js
83 lines (69 loc) · 1.87 KB
/
queue.js
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
76
77
78
79
80
81
82
83
Queue = {}
Queue.config = {}
Queue.pending = new Mongo.Collection("queuePending");
Queue.posted = new Mongo.Collection("queuePosted");
Queue.register = function (config) {
keys = Object.keys(config);
keys.forEach(function (key) {
Queue.config[key] = config[key];
});
}
Queue.add = function (name, data) {
if (Queue.config[name]) {
doc = {
name: name,
data: data,
date: new Date()
}
if (Meteor.userId()) {
doc.userId = Meteor.userId();
}
Queue.collection.insert(doc);
} else {
console.log("Queue Error: '" + name + "' does not exist");
}
}
Queue.addToHistory = function (doc, action, extraData, result) {
doc = {
original: doc,
action: action,
extraData: extraData,
result: result
};
if (Meteor.userId) {
userId: Meteor.userId();
}
Queue.posted.insert(doc)
}
Queue.resolve = function (id, action, extraData) {
// First, we get the document of the item in the queue
doc = Queue.collection.findOne(id)
if (doc) {
// Then, we want to remove the document to minimize the risk of it being called twice
remove = Queue.collection.remove(id);
// Assume the remove returns 1, we can assume we are the only ones to touch it
if (remove === 1) {
try {
result = Queue.config[doc.name][action](doc.data, extraData);
// assuming the function above ran successfully, we add the item to history
if (result) {
Queue.addToHistory(doc, action, extraData, result)
}
return result;
} catch (e) {
// If the function failed for whatever reason, we put the item back in the queue
Queue.collection.insert(doc);
}
}
} else {
console.log("Queue Error: item '" + id + "' was not found.");
return false;
}
}
Queue.resolveAll = function (id, action, extraData) {
doc = Queue.collection.findOne(id)
doc.data;
docs.find({data: docData}).fetch().forEach(function (item) {
Queue.resolve(item._id, action, extraData)
});
}