-
Notifications
You must be signed in to change notification settings - Fork 0
/
parasoupCache.js
74 lines (70 loc) · 2.59 KB
/
parasoupCache.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
var mongoHelper = require("./mongoHelper.js"),
Collection = require('mongodb').Collection;
var createCache = function(options, initcb) {
if (!options) {
initcb(new Error("missing options"));
return;
}
var db;
var collection;
mongoHelper.open(options, function(err, tdb) {
if (err) {
initcb(err);
} else {
db = tdb;
collection = new Collection(db, 'parasoup.cache');
var api = {
getAndRemoveItem: function(cb) {
collection.find({}).limit(1000).count(function(err, count) {
if (err) {
cb(err);
} else if (count === 0) {
cb(null, null);
} else {
var randomNumber = Math.floor(Math.random() * count);
collection.find(
{},
{
"_id": 1,
"filename": 1
},
{
limit: 1,
skip: randomNumber
}
).nextObject(
function(err, doc) {
if (err) {
cb(err);
} else {
collection.remove(
{ "_id": doc._id },
function() {
cb(null, doc.filename);
}
);
}
}
);
}
});
},
insert: function(filename, cb) {
collection.update(
{ filename: filename },
{ $set: { filename: filename } },
{ upsert: true, safe: true },
function(err) {
cb(err);
}
);
},
size: function(cb) {
collection.find({}).count(cb);
}
};
initcb(null, api);
}
});
};
module.exports = createCache;