-
Notifications
You must be signed in to change notification settings - Fork 10
/
access.js
54 lines (50 loc) · 1.44 KB
/
access.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
//access.js
module.exports.saveBook = function(db, title, author, text, callback) {
db.collection('text').save({title:title, author:author, text:text}, callback);
};
module.exports.findBookByTitle = function(db, title, callback) {
db.collection('text').findOne({title:title}, function(err, doc) {
if (err || !doc)
callback(null);
else
callback(doc.text);
});
};
module.exports.findBookByTitleCached = function(db, redis, title, callback) {
redis.get(title, function(err, reply) {
if (err)
callback(null);
else if (reply) //Book exists in cache
callback(JSON.parse(reply));
else {
//Book doesn't exist in cache - we need to query the main database
db.collection('text').findOne({title:title}, function(err, doc) {
if (err || !doc)
callback(null);
else {
\\Book found in database, save to cache and return to client
redis.set(title, JSON.stringify(doc), function() {
callback(doc);
});
}
});
}
});
};
module.exports.access.updateBookByTitle = function(db, redis, title, newText, callback) {
db.collection("text").findAndModify({title:title}, {$set:{text:text}}, function (err, doc) { //Update the main database
if(err)
callback(err);
else if (!doc)
callback('Missing book');
else {
//Save new book version to cache
redis.set(title, JSON.stringify(doc), function(err) {
if(err)
callback(err);
else
callback(null);
});
}
});
};