-
Notifications
You must be signed in to change notification settings - Fork 25
/
counter.coffee
59 lines (45 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
50
51
52
53
54
55
56
57
58
59
getRawMongoCollection = (collectionName) ->
if MongoInternals?
MongoInternals.defaultRemoteCollectionDriver().mongo._getCollection(collectionName)
else
Meteor._RemoteCollectionDriver.mongo._getCollection(collectionName)
getCounterCollection = ->
getRawMongoCollection('awwx_mongo_counter')
callCounter = (method, args...) ->
Counters = getCounterCollection()
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()
_deleteCounters = ->
callCounter('remove', {}, {safe: true})
_incrementCounter = (counterName, amount = 1) ->
newDoc = callCounter(
'findAndModify',
{_id: counterName}, # query
null, # sort
{$inc: {seq: amount}}, # update
{new: true, upsert: true}, # options
) # callback added by wrapAsync
return newDoc.seq
_decrementCounter = (counterName, amount = 1) ->
_incrementCounter(counterName, -amount)
_setCounter = (counterName, value) ->
callCounter(
'update',
{_id: counterName},
{$set: {seq: value}}
)
return
if Package?
incrementCounter = _incrementCounter
decrementCounter = _decrementCounter
setCounter = _setCounter
deleteCounters = _deleteCounters
else
@incrementCounter = _incrementCounter
@decrementCounter = _decrementCounter
@setCounter = _setCounter
@deleteCounters = _deleteCounters