forked from konecty/meteor-mongo-counter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
counter.coffee
41 lines (32 loc) · 1.19 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
getCounterCollection = (collection) ->
collection.rawCollection()
callCounter = (method, collection, args...) ->
Counters = getCounterCollection(collection)
if Meteor.wrapAsync?
Meteor.wrapAsync(_.bind(Counters[method], Counters))(args...)
else
future = new (Npm.require(Npm.require('path').join('fibers', 'future')))()
Counters[method].call(Counters, args..., future.resolver())
future.wait()
export deleteCounters = (collection) ->
callCounter('remove', collection, {}, {safe: true})
export incrementCounter = (collection, counterName, amount = 1) ->
newDoc = callCounter(
'findAndModify',
collection,
{_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
export decrementCounter = (collection, counterName, amount = 1) ->
incrementCounter(collection, counterName, -amount)
export setCounter = (collection, counterName, value) ->
callCounter(
'update',
collection,
{_id: counterName},
{$set: {next_val: value}}
)
return