54 lines
1.2 KiB
Go
54 lines
1.2 KiB
Go
package entity
|
|
|
|
import (
|
|
"errors"
|
|
"time"
|
|
|
|
"go.mongodb.org/mongo-driver/v2/bson"
|
|
)
|
|
|
|
type AutoID struct {
|
|
ID bson.ObjectID `bson:"_id,omitempty" json:"id,omitempty"`
|
|
Name string `bson:"name,omitempty" json:"name,omitempty"`
|
|
Counter uint64 `bson:"counter" json:"counter"`
|
|
UpdateAt *int64 `bson:"update_at,omitempty" json:"update_at,omitempty"`
|
|
CreateAt *int64 `bson:"create_at,omitempty" json:"create_at,omitempty"`
|
|
}
|
|
|
|
func (a *AutoID) CollectionName() string {
|
|
return "count"
|
|
}
|
|
|
|
// Validate validates the AutoID entity
|
|
func (a *AutoID) Validate() error {
|
|
if a.Name == "" {
|
|
return errors.New("name is required")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// SetTimestamps sets the create and update timestamps
|
|
func (a *AutoID) SetTimestamps() {
|
|
now := time.Now().UTC().UnixNano()
|
|
if a.CreateAt == nil {
|
|
a.CreateAt = &now
|
|
}
|
|
a.UpdateAt = &now
|
|
}
|
|
|
|
// IsNew returns true if this is a new counter (no ID set)
|
|
func (a *AutoID) IsNew() bool {
|
|
return a.ID.IsZero()
|
|
}
|
|
|
|
// GetIDString returns the ID as a hex string
|
|
func (a *AutoID) GetIDString() string {
|
|
return a.ID.Hex()
|
|
}
|
|
|
|
// Increment increments the counter by 1
|
|
func (a *AutoID) Increment() {
|
|
a.Counter++
|
|
a.SetTimestamps()
|
|
}
|