Skip to content

Instantly share code, notes, and snippets.

@Solution
Created May 13, 2021 13:22
Show Gist options
  • Save Solution/62f54b11674776f6ddd4e18f31d52a6c to your computer and use it in GitHub Desktop.
Save Solution/62f54b11674776f6ddd4e18f31d52a6c to your computer and use it in GitHub Desktop.
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