-
Notifications
You must be signed in to change notification settings - Fork 0
/
urlDao.js
73 lines (67 loc) · 2.34 KB
/
urlDao.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
const mongo = require("mongodb").MongoClient;
const sequenceDao = require("./sequenceDao.js");
//var dbUrl = "mongodb://localhost:27017/urlshortener-fcc-api";
var dbUrl = process.env.SHORTENER_APP_DB_URL;
module.exports = {
find: function find(url, callback) {
console.log("Env variable DAO SHORTENER_APP_DB_URL = " + dbUrl);
mongo.connect(dbUrl, handleFindUrl.bind(null, url, callback));
},
findBySequence: function findBySequence(sequence, callback) {
console.log("Env variable DAO SHORTENER_APP_DB_URL = " + dbUrl);
mongo.connect(dbUrl, handleFindBySequence.bind(null, sequence, callback));
},
save: function save(url, callback) {
console.log("Env variable DAO SHORTENER_APP_DB_URL = " + dbUrl);
mongo.connect(dbUrl, handleSaveUrl.bind(null, url, callback));
}
};
function handleFindBySequence(sequence, callback, err, db) {
if (err) {
throw err;
} else {
var collectionName = "url";
var urlColl = db.collection(collectionName);
urlColl.find({seq: parseInt(sequence)}).toArray(function(err, documents) {
if (err) {
throw err;
}
return callback(documents);
db.close; // Refactor. Find better place to close it!!
});
}
}
function handleFindUrl(url, callback, err, db) {
if (err) {
throw err;
} else {
var collectionName = "url";
var urlColl = db.collection(collectionName);
urlColl.find({"url": url}).toArray(function(err, documents) {
if (err) {
throw err;
}
return callback(documents);
db.close; // Refactor. Find better place to close it!!
});
}
}
function handleSaveUrl(url, callback, err, db) {
if (err) {
throw err;
} else {
var collectionName = "url";
sequenceDao.getNextSequence(collectionName, db, saveUrl.bind(null, collectionName, url, callback, db));
}
}
function saveUrl(collectionName, url, callback, db, sequence) {
var urlObject = {seq: sequence, "url": url};
var urlColl = db.collection(collectionName);
urlColl.insert(urlObject, function(err, data) {
if (err) {
throw err;
}
db.close; // Refactor. Find better place to close it!!
return callback(sequence);
});
}