Save method

This commit is contained in:
Eden Kirin
2024-06-26 11:20:26 +02:00
parent bdc978aec1
commit 450345ba6b
2 changed files with 36 additions and 1 deletions

View File

@ -0,0 +1,31 @@
package repository
import (
"repo-pattern/app/repository/smartfilter"
"gorm.io/gorm/schema"
)
type DeleteMethod[T schema.Tabler] struct {
repo *RepoBase[T]
}
func (m *DeleteMethod[T]) Init(repo *RepoBase[T]) {
m.repo = repo
}
func (m DeleteMethod[T]) Delete(filter interface{}) (int64, error) {
var (
model T
)
query, err := smartfilter.ToQuery(model, filter, m.repo.dbConn)
if err != nil {
return 0, err
}
result := query.Delete(&model)
if result.Error != nil {
return 0, result.Error
}
return result.RowsAffected, nil
}

View File

@ -5,6 +5,8 @@ import (
"gorm.io/gorm/schema" "gorm.io/gorm/schema"
) )
const DEFAULT_ID_FIELD = "id"
type MethodInitInterface[T schema.Tabler] interface { type MethodInitInterface[T schema.Tabler] interface {
Init(repo *RepoBase[T]) Init(repo *RepoBase[T])
} }
@ -22,6 +24,7 @@ type RepoBase[T schema.Tabler] struct {
ExistsMethod[T] ExistsMethod[T]
CountMethod[T] CountMethod[T]
SaveMethod[T] SaveMethod[T]
DeleteMethod[T]
} }
func (repo *RepoBase[T]) InitMethods(methods []MethodInitInterface[T]) { func (repo *RepoBase[T]) InitMethods(methods []MethodInitInterface[T]) {
@ -35,7 +38,7 @@ func (m *RepoBase[T]) Init(dbConn *gorm.DB, options *RepoOptions) {
if options == nil { if options == nil {
// no options provided? set defaults // no options provided? set defaults
m.IdField = "id" m.IdField = DEFAULT_ID_FIELD
} else { } else {
if len(options.IdField) > 0 { if len(options.IdField) > 0 {
m.IdField = options.IdField m.IdField = options.IdField
@ -48,6 +51,7 @@ func (m *RepoBase[T]) Init(dbConn *gorm.DB, options *RepoOptions) {
&m.ExistsMethod, &m.ExistsMethod,
&m.CountMethod, &m.CountMethod,
&m.SaveMethod, &m.SaveMethod,
&m.DeleteMethod,
} }
m.InitMethods(methods) m.InitMethods(methods)
} }