-
Notifications
You must be signed in to change notification settings - Fork 82
/
ShortURL.js
executable file
·79 lines (69 loc) · 1.83 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
75
76
77
78
79
/**
*
* Mongoose Model:
* - ShortURL
*
*/
var mongoose = require('mongoose')
, Schema = mongoose.Schema
, ObjectId = Schema.ObjectId;
var ShortURLSchema = new Schema({
id : { 'type' : ObjectId },
URL : { 'type' : String },
qr : { 'type' : String },
hash : { 'type' : String, unique: true },
hits : { 'type' : Number, 'default': 0 },
created_at : { 'type' : Date, 'default': Date.now },
uniques : { 'type' : Number, 'default': 0},
visitors : { 'type' : [String]},
data : { 'any' : Schema.Types.Mixed }
});
var ShortURL = mongoose.model('ShortURL', ShortURLSchema);
/**
* @model ShortURL
* @method findByHash
* @param {String} hash
* @param {Function} callback
*/
ShortURL.findByHash = function (hash, options, callback) {
options.hash = hash;
ShortURL.findOne({ hash: hash }, function (error, URL) {
if (error) {
callback(error, null);
} else {
if (URL) {
ShortURL.updateHitsById(URL, options, callback);
} else {
callback(null, null);
}
}
});
};
/**
* @model ShortURL
* @method updatehitsById
* @param {ObjectId} id
* @param {Function} callback
*/
ShortURL.updateHitsById = function (URL, options, callback) {
if (options && options.visitor && URL.visitors.indexOf(options.visitor) === -1) {
ShortURL.update({'hash': options.hash}, {
$inc: {hits: 1, uniques: 1}, $push: {visitors: options.visitor}}, { multi: true}, function (error) {
if (error) {
callback(error, null);
} else {
callback(null, URL);
}
});
} else {
ShortURL.update({'hash': options.hash}, { $inc: {hits: 1}}, { multi: true}, function (error) {
if (error) {
callback(error, null);
} else {
callback(null, URL);
}
});
}
};
module.exports = ShortURL;
/* EOF */