Skip to content

Commit

Permalink
Merge pull request #8 from ataklychev/master
Browse files Browse the repository at this point in the history
normalize empty error from gorm to nil
  • Loading branch information
mnvx authored Jun 25, 2024
2 parents e663b54 + db2c6ac commit 7717db9
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
6 changes: 4 additions & 2 deletions crud_repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ func (c CrudRepository) GetModel() InterfaceEntity {
func (c CrudRepository) Find(id uint) (InterfaceEntity, error) {
item := reflect.New(reflect.TypeOf(c.GetModel()).Elem()).Interface()
err := c.Db.First(item, id).Error
return item, err
return item, NormalizeErr(err)
}

func (c CrudRepository) PluckBy(fieldNames []string) (map[string]int64, error) {
Expand Down Expand Up @@ -232,7 +232,7 @@ func (c CrudRepository) List(parameters ListParametersInterface) ([]InterfaceEnt
data = append(data, sliceValue.Index(i).Interface())
}

return data, err
return data, NormalizeErr(err)
}

func (c CrudRepository) Create(item InterfaceEntity) InterfaceEntity {
Expand Down Expand Up @@ -361,6 +361,7 @@ func (c CrudRepository) CreateOrUpdateMany(
onConflict)

err := c.Db.Exec(query).Error
err = NormalizeErr(err)
if nil != err {
c.Logger.Errorf("gorm-crud: Error in the CreateOrUpdateMany(): %v", err)
}
Expand All @@ -375,6 +376,7 @@ func (c CrudRepository) Update(item InterfaceEntity) InterfaceEntity {

func (c CrudRepository) Delete(id uint) error {
item, err := c.Find(id)
err = NormalizeErr(err)
if err != nil {
return err
}
Expand Down
19 changes: 19 additions & 0 deletions helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package gorm_crud

import (
"fmt"
"reflect"
"strconv"
)

Expand All @@ -14,3 +15,21 @@ func Num64(n interface{}) int64 {
return i
}
}

func IsNil(i interface{}) bool {
if i == nil {
return true
}
switch reflect.TypeOf(i).Kind() {
case reflect.Ptr, reflect.Map, reflect.Array, reflect.Chan, reflect.Slice:
return reflect.ValueOf(i).IsNil()
}
return false
}

func NormalizeErr(err error) error {
if IsNil(err) {
return nil
}
return err
}

0 comments on commit 7717db9

Please sign in to comment.