☙◦ The Tablet ❀ GamerGirlandCo ◦❧
924b3fc9d2
- add support for `autoinc` struct tag - add Pull method to Model - add utility func to increment a value of an unknown type by 1 - idcounter.go no longer increments the counter value (it is now up to the caller to increment the returned value themselves)
45 lines
940 B
Go
45 lines
940 B
Go
package orm
|
|
|
|
import (
|
|
"context"
|
|
"reflect"
|
|
|
|
"go.mongodb.org/mongo-driver/bson"
|
|
"go.mongodb.org/mongo-driver/bson/primitive"
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
)
|
|
|
|
const COUNTER_COL = "@counters"
|
|
|
|
type Counter struct {
|
|
Current any `bson:"current"`
|
|
Collection string `bson:"collection"`
|
|
}
|
|
|
|
func getLastInColl(cname string, id interface{}) interface{} {
|
|
var opts *options.FindOneOptions = options.FindOne()
|
|
|
|
switch id.(type) {
|
|
case int, int64, int32, uint, uint32, uint64, primitive.ObjectID:
|
|
opts.SetSort(bson.M{"_id": -1})
|
|
case string:
|
|
opts.SetSort(bson.M{"createdAt": -1})
|
|
default:
|
|
panic("unsupported id type provided")
|
|
}
|
|
|
|
var cnt Counter
|
|
if !reflect.ValueOf(id).IsZero() {
|
|
return id
|
|
}
|
|
if err := DB.Collection(COUNTER_COL).FindOne(context.TODO(), bson.M{
|
|
"collection": cname,
|
|
}, opts).Decode(&cnt); err != nil {
|
|
cnt = Counter{
|
|
Current: id,
|
|
}
|
|
cnt.Collection = cname
|
|
}
|
|
return cnt.Current
|
|
}
|