forked from konecty/meteor-mongo-counter
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcounter.coffee
49 lines (40 loc) · 1.53 KB
/
counter.coffee
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
callCounter = (method, collectionName, args...) ->
# TODO: How about pass not only collection name, but mongo instance
# like MongoInternals.RemoteCollectionDriver("mongodb://127.0.0.1:3001/meteor");
# However I don't need use several database for counters
mongo = MongoInternals.defaultRemoteCollectionDriver().mongo
Counters = mongo.rawCollection(collectionName)
Meteor.wrapAsync(_.bind(Counters[method], Counters))(args...)
_deleteCounters = (collectionName) ->
callCounter('remove', collectionName, {}, {safe: true})
_incrementCounter = (collectionName, counterName, amount = 1) ->
newDoc = callCounter(
'findAndModify',
collectionName,
{_id: counterName}, # query
null, # sort
{$inc: {next_val: amount}}, # update
{new: true, upsert: true}, # options
) # callback added by wrapAsync
return newDoc?.value?.next_val or newDoc.next_val
_decrementCounter = (collectionName, counterName, amount = 1) ->
_incrementCounter(collectionName, counterName, -amount)
_setCounter = (collectionName, counterName, value) ->
callCounter(
'update',
collectionName,
{_id: counterName},
{$set: {next_val: value}},
{upsert: true}
)
return
if Package?
incrementCounter = _incrementCounter
decrementCounter = _decrementCounter
setCounter = _setCounter
deleteCounters = _deleteCounters
else
@incrementCounter = _incrementCounter
@decrementCounter = _decrementCounter
@setCounter = _setCounter
@deleteCounters = _deleteCounters