mgocrud/interface.go

68 lines
1.5 KiB
Go
Raw Permalink Normal View History

2018-03-20 14:16:01 +01:00
package mgocrud
import (
"reflect"
"strings"
"time"
"gopkg.in/mgo.v2/bson"
)
// ModelInterface is interface for mgo crud operations
type ModelInterface interface {
PrepareInsert()
PrepareUpdate()
GetID() *bson.ObjectId
SetID(id *bson.ObjectId)
GetIdentSelector() (selector bson.M)
SetIdent()
}
// Model is model with default fields
type Model struct {
ID *bson.ObjectId `json:"id,omitempty" bson:"_id" mapstructure:"id"`
InsertTime *time.Time `json:"insertTime,omitempty" bson:"insertTime,omitempty" index:"single" mapstructure:"Datum"`
UpdateTime *time.Time `json:"updateTime,omitempty" bson:"updateTime,omitempty" index:"single" mapstructure:"Datum"`
2018-03-20 14:16:01 +01:00
Ident []string `json:"ident,omitempty" bson:"-" mapstructure:"-"`
}
// GetCollectionName gets name from type
func GetCollectionName(m ModelInterface) string {
if i, ok := m.(interface {
GetCollectionName() string
}); ok {
return i.GetCollectionName()
}
return strings.ToLower(
reflect.TypeOf(
reflect.Indirect(reflect.ValueOf(m)).Interface(),
).Name())
}
// PrepareInsert creates new bson id and insert time
func (m *Model) PrepareInsert() {
2019-09-17 10:58:04 +02:00
if m.ID == nil {
id := bson.NewObjectId()
m.ID = &id
}
2018-03-20 14:16:01 +01:00
now := time.Now()
m.InsertTime = &now
m.UpdateTime = &now
}
// PrepareUpdate updates UpdateTime
func (m *Model) PrepareUpdate() {
now := time.Now()
m.UpdateTime = &now
}
// GetID gets object id
func (m *Model) GetID() *bson.ObjectId {
return m.ID
}
// SetID sets object id
func (m *Model) SetID(id *bson.ObjectId) {
m.ID = id
}