Long overdue initial commit
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
package counter
|
||||
|
||||
import (
|
||||
"git.aiterp.net/rpdata/api/internal/store"
|
||||
"github.com/globalsign/mgo"
|
||||
"github.com/globalsign/mgo/bson"
|
||||
)
|
||||
|
||||
var collection *mgo.Collection
|
||||
|
||||
type counter struct {
|
||||
ID string `bson:"_id"`
|
||||
Value int `bson:"value"`
|
||||
}
|
||||
|
||||
// Next gets the next value of a counter, or an error if it hasn't.
|
||||
func Next(category, name string) (int, error) {
|
||||
id := category + "." + name
|
||||
doc := counter{}
|
||||
|
||||
_, err := collection.Find(bson.M{"_id": id}).Apply(mgo.Change{
|
||||
Update: bson.M{"$inc": bson.M{"value": 1}},
|
||||
Upsert: true,
|
||||
ReturnNew: true,
|
||||
}, &doc)
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
|
||||
return doc.Value, nil
|
||||
}
|
||||
|
||||
func init() {
|
||||
store.HandleInit(func(db *mgo.Database) {
|
||||
collection = db.C("core.counters")
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package counter_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.aiterp.net/rpdata/api/internal/store"
|
||||
"git.aiterp.net/rpdata/api/model/counter"
|
||||
)
|
||||
|
||||
func TestCounter(t *testing.T) {
|
||||
store.Init()
|
||||
|
||||
value, err := counter.Next("test", "times_tested")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
t.Log("Value:", value)
|
||||
}
|
||||
Reference in New Issue
Block a user