-
Notifications
You must be signed in to change notification settings - Fork 82
/
ShortURL.js
executable file
·74 lines (64 loc) · 1.55 KB
/
ShortURL.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
/*
*
* Model::ShortURL
*
*/
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var shortURL_schema = {
id : ObjectId,
URL : String,
hash : { type : String },
hits : { type : Number, default: 0 },
created_at : { type : Date, default: Date.now }
};
var ShortURLSchema = new Schema(shortURL_schema);
var ShortURL = mongoose.model("ShortURL", ShortURLSchema);
// return count, if it exists, try another
ShortURL.checkExists = function(hash, callback) {
var query = ShortURL.find({});
query.where("hash", hash);
query.exec(function(error, shortenedURLS) {
if (error) {
callback(error, null);
} else {
callback(null, shortenedURLS);
};
});
};
// search for a URL by its hash
ShortURL.findByHash = function(hash, callback) {
ShortURL.find({ hash: hash }, function(error, URL) {
if (error) {
callback(error, null);
} else {
if (URL.length !== 0) {
var id = URL[0]._id;
ShortURL.updateHitsById(id, function(error) {
if (error) {
callback(error, null);
} else {
callback(null, URL);
};
});
} else {
callback(null, null);
}
};
});
};
// increment hits
ShortURL.updateHitsById = function(id, callback) {
ShortURL.findById(id, function (error, URL) {
var hits = URL.hits + 1;
if (!error) {
URL.hits = hits;
URL.save(function(error) {
callback(error);
});
}
});
};
module.exports = ShortURL;
/* EOF */