Repo options

This commit is contained in:
Eden Kirin
2024-06-25 01:19:40 +02:00
parent c2bcbea5d2
commit 4615d55309
8 changed files with 112 additions and 37 deletions

View File

@ -5,25 +5,42 @@ import (
"gorm.io/gorm/schema"
)
type MethodInitInterface interface {
Init(dbConn *gorm.DB)
type MethodInitInterface[T schema.Tabler] interface {
Init(repo *RepoBase[T])
}
type RepoOptions struct {
IdField string
}
type RepoBase[T schema.Tabler] struct {
DbConn int
IdField string
dbConn *gorm.DB
ListMethod[T]
GetMethod[T]
ExistsMethod[T]
methods []MethodInitInterface
methods []MethodInitInterface[T]
}
func (b *RepoBase[T]) InitMethods(dbConn *gorm.DB) {
for _, method := range b.methods {
method.Init(dbConn)
func (repo *RepoBase[T]) InitMethods(dbConn *gorm.DB) {
for _, method := range repo.methods {
method.Init(repo)
}
}
func (m *RepoBase[T]) Init(dbConn *gorm.DB) {
m.methods = []MethodInitInterface{&m.ListMethod, &m.GetMethod, &m.ExistsMethod}
func (m *RepoBase[T]) Init(dbConn *gorm.DB, options *RepoOptions) {
m.dbConn = dbConn
if options == nil {
// no options provided? set defaults
m.IdField = "id"
} else {
if len(options.IdField) > 0 {
m.IdField = options.IdField
}
}
m.methods = []MethodInitInterface[T]{&m.ListMethod, &m.GetMethod, &m.ExistsMethod}
m.InitMethods(dbConn)
}