Created
May 13, 2021 13:22
-
-
Save Solution/62f54b11674776f6ddd4e18f31d52a6c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Repository struct { | |
database *gorm.DB | |
} | |
func NewRepository(database *gorm.DB) Repository { | |
return Repository{database: database} | |
} | |
func (r Repository) NewQueryObject() *QueryObject { | |
return NewQueryObject(r.database.Session(&gorm.Session{NewDB: true})) | |
} | |
func (r Repository) FindOne(query *QueryObject) (*models.User, error) { | |
var u models.User | |
res := query.GetQuery().First(&u) | |
if res.Error != nil && !errors.Is(res.Error, gorm.ErrRecordNotFound) { | |
return nil, res.Error | |
} | |
if errors.Is(res.Error, gorm.ErrRecordNotFound) { | |
return nil, nil | |
} | |
return &u, nil | |
} | |
func (r Repository) Exists(query *QueryObject) (bool, error) { | |
q := query.GetQuery().Select("id") | |
var id uint | |
res := q.Find(&id) | |
if res.Error != nil && !errors.Is(res.Error, gorm.ErrRecordNotFound) { | |
return false, res.Error | |
} | |
return id != 0, nil | |
} | |
func (r Repository) FindAll(query *QueryObject) ([]models.User, error) { | |
var users = make([]models.User, 0) | |
res := query.GetQuery().Find(&users) | |
if res.Error != nil && !errors.Is(res.Error, gorm.ErrRecordNotFound) { | |
return nil, res.Error | |
} | |
return users, nil | |
} | |
func (r Repository) Count(query *QueryObject) (int64, error) { | |
var totalCount int64 | |
res := query.GetQuery().Count(&totalCount) | |
if res.Error != nil { | |
return 0, res.Error | |
} | |
return totalCount, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment