| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- package bson
-
- import (
- "time"
-
- "git.x2erp.com/qdy/go-base/ctx"
- "go.mongodb.org/mongo-driver/bson/primitive"
- )
-
- // IDType 泛型类型约束
- type IDType interface {
- string | primitive.ObjectID
- }
-
- // 泛型内部模型
- type bsonModel[T IDType] struct {
- ID T `bson:"_id,omitempty" json:"id,omitempty"`
- TenantId string `bson:"tenant_id,omitempty"`
- CreatedBy string `bson:"created_by,omitempty" json:"created_by,omitempty"`
- CreatedAt time.Time `bson:"created_at" json:"created_at"`
- UpdatedBy string `bson:"updated_by,omitempty" json:"updated_by,omitempty"`
- UpdatedAt time.Time `bson:"updated_at" json:"updated_at"`
- }
-
- // 保持原有的外部类型
- type BsonStringModel = bsonModel[string]
- type BsonObjectModel = bsonModel[primitive.ObjectID]
-
- // 创建新的 String 模型(自动生成ID)
- func NewStringIDModel(ctx ctx.RequestContext) BsonStringModel {
- return BsonStringModel{
- ID: primitive.NewObjectID().Hex(),
- TenantId: ctx.TenantID,
- CreatedAt: time.Now(),
- CreatedBy: ctx.UserID,
- UpdatedAt: time.Now(),
- UpdatedBy: ctx.UserID,
- }
- }
-
- // 创建新的 String 模型(自定义ID)
- func NewStringIDModelWithID(ctx ctx.RequestContext, id string) BsonStringModel {
- return BsonStringModel{
- ID: id,
- TenantId: ctx.TenantID,
- CreatedAt: time.Now(),
- CreatedBy: ctx.UserID,
- UpdatedAt: time.Now(),
- UpdatedBy: ctx.UserID,
- }
- }
-
- // 创建新的 ObjectID 模型(自动生成ID)
- func NewObjectIDModel(ctx ctx.RequestContext) BsonObjectModel {
- return BsonObjectModel{
- ID: primitive.NewObjectID(),
- TenantId: ctx.TenantID,
- CreatedAt: time.Now(),
- CreatedBy: ctx.UserID,
- UpdatedAt: time.Now(),
- UpdatedBy: ctx.UserID,
- }
- }
-
- // 用于更新操作的模型(只设置更新信息)
- func ModelForUpdate(ctx ctx.RequestContext) BsonStringModel {
- return BsonStringModel{
- UpdatedAt: time.Now(),
- UpdatedBy: ctx.UserID,
- }
- }
|