This commit is contained in:
Eden Kirin
2024-06-25 00:49:13 +02:00
parent ff51420b71
commit c2bcbea5d2
3 changed files with 75 additions and 4 deletions

View File

@ -9,6 +9,7 @@ import (
type GetOptions struct { type GetOptions struct {
Only *[]string Only *[]string
RaiseError *bool
} }
type GetMethod[T schema.Tabler] struct { type GetMethod[T schema.Tabler] struct {
@ -34,9 +35,12 @@ func (m GetMethod[T]) Get(filter interface{}, options *GetOptions) (*T, error) {
} }
result := query.First(&model) result := query.First(&model)
if result.Error != nil { if result.Error == nil {
return nil, result.Error return &model, nil
} }
return &model, nil if options != nil && options.RaiseError != nil && *options.RaiseError {
return nil, result.Error
}
return nil, nil
} }

View File

@ -0,0 +1,67 @@
package repository
import (
"fmt"
"regexp"
"testing"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
)
func TestGetMethod(t *testing.T) {
t.Run("With id filter, suppress errors", func(t *testing.T) {
sqldb, db, mock := NewMockDB()
defer sqldb.Close()
repo := RepoBase[MyModel]{}
repo.Init(db)
id := uuid.New()
filter := MyModelFilter{
Id: &id,
}
options := GetOptions{}
sql := "SELECT * FROM my_models WHERE my_models.id = $1 ORDER BY my_models.id LIMIT $2"
mock.ExpectQuery(fmt.Sprintf("^%s$", regexp.QuoteMeta(sql))).WithArgs(id, 1)
result, err := repo.Get(filter, &options)
assert.Nil(t, result)
assert.Nil(t, err)
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expectations: %s", err)
}
})
t.Run("With id filter, raise error", func(t *testing.T) {
sqldb, db, mock := NewMockDB()
defer sqldb.Close()
repo := RepoBase[MyModel]{}
repo.Init(db)
id := uuid.New()
raiseError := true
filter := MyModelFilter{
Id: &id,
}
options := GetOptions{
RaiseError: &raiseError,
}
sql := "SELECT * FROM my_models WHERE my_models.id = $1 ORDER BY my_models.id LIMIT $2"
mock.ExpectQuery(fmt.Sprintf("^%s$", regexp.QuoteMeta(sql))).
WithArgs(id, 1).
WillReturnError(nil)
result, err := repo.Get(filter, &options)
assert.Nil(t, result)
assert.NotNil(t, err)
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expectations: %s", err)
}
})
}