-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathindex.js
108 lines (83 loc) · 2.34 KB
/
index.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/**
* Module dependencies.
*/
var mongoose = require('mongoose')
, ObjectId = mongoose.Schema.ObjectId;
/**
* Expose mongoose voting
*/
module.exports = exports = voting;
/**
* Mongoose Voting Plugin
*
* @param {Schema} schema MongooseSchema
* @param {Object} options for plugin configuration
* @api public
*/
function voting (schema, options) {
options || ( options = {} );
var voterModelName = options.ref || 'User';
schema.add({
vote: {
positive: [{ type: ObjectId, ref: voterModelName }],
negative: [{ type: ObjectId, ref: voterModelName }]
}
});
schema.methods.upvote = function upvote(user, fn) {
// Reset vote if existed
this.vote.negative.pull(user);
// Upvote
this.vote.positive.addToSet(user);
// If callback fn, save and return
if (2 === arguments.length) {
this.save(fn);
};
};
schema.methods.downvote = function downvote(user, fn) {
// Reset vote if existed
this.vote.positive.pull(user);
// Downvote
this.vote.negative.addToSet(user);
// If callback fn, save and return
if (2 === arguments.length) {
this.save(fn);
};
};
schema.methods.unvote = function unvote(user, fn) {
this.vote.negative.pull(user);
this.vote.positive.pull(user);
// If callback fn, save and return
if (2 === arguments.length) {
this.save(fn);
};
}
schema.methods.upvoted = function upvoted(user) {
if (user._id) {
return schema.methods.upvoted.call(this, user._id);
};
return !!~this.vote.positive.indexOf(user);
};
schema.methods.downvoted = function downvoted(user) {
if (user._id) {
return schema.methods.downvoted.call(this, user._id);
};
return !!~this.vote.negative.indexOf(user);
};
schema.methods.voted = function voted(user) {
if (user._id) {
return schema.methods.voted.call(this, user._id);
};
return schema.methods.upvoted.call(this, user) || schema.methods.downvoted.call(this, user);
}
schema.methods.upvotes = function upvotes() {
return this.vote.positive.length;
}
schema.methods.downvotes = function upvotes() {
return this.vote.negative.length;
}
schema.methods.votes = function upvotes() {
var positives = this.vote.positive;
var negatives = this.vote.negative;
return [].concat(positives).concat(negatives).length;
}
}