diamond-orm/idcounter.go

45 lines
902 B
Go
Raw Normal View History

2024-09-01 16:17:48 -04:00
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{} {
2024-09-14 15:20:17 -04:00
var opts = options.FindOne()
2024-09-01 16:17:48 -04:00
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:
2024-09-14 15:20:17 -04:00
panic(ErrUnsupportedID)
2024-09-01 16:17:48 -04:00
}
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
}