forked from awwx/meteor-mongo-counter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcounter.js
50 lines (42 loc) · 1.44 KB
/
counter.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
// counter.js
// Converted from counter.coffee
//
const getCounterCollection = (collection) => collection.rawCollection()
const callCounter = function (method, collection, ...args) {
const Counters = getCounterCollection(collection)
return Meteor.wrapAsync(Counters[method].bind(Counters))(...Array.from(args || []))
}
const _deleteCounters = (collection) =>
callCounter('remove', collection, {}, { safe: true })
const _incrementCounter = function (collection, counterName, amount) {
if (amount == null) {
amount = 1
}
const newDoc = callCounter(
'findAndModify',
collection,
{ _id: counterName }, // query
null, // sort
{ $inc: { next_val: amount } }, // update
{ new: true, upsert: true } // options
) // callback added by wrapAsync
if (newDoc && newDoc.value && newDoc.value.next_val) {
return newDoc.value.next_val
}
return null
}
const _decrementCounter = function (collection, counterName, amount) {
if (amount == null) {
amount = 1
}
return _incrementCounter(collection, counterName, -amount)
}
const _setCounter = function (collection, counterName, value) {
callCounter('update', collection, { _id: counterName }, { $set: { next_val: value } })
}
// Any variables defined without const/var/let are 'published' for the package... this is
// done in package.js
incrementCounter = _incrementCounter
decrementCounter = _decrementCounter
setCounter = _setCounter
deleteCounters = _deleteCounters