samedi 25 septembre 2021

Gorm Find result to interface

I am trying to build a generic CrudRepository struct using Gorm for my api. I know generics are coming to GoLang in version 2 but I try to build this lib using reflection or any other lib.

In my CrudRepository:

func (repository *BaseRepository) find(result interface{}, pageSize int, page int) error {
  if page < 1 {
    return errors.ExceedsMinimumInt("page", "", 0, true, nil)
  }

  offset := (page - 1) * pageSize

  ent := reflect.Zero(reflect.TypeOf(result))

  repository.db = repository.db.Limit(pageSize).Offset(offset)
  err := repository.db.Find(&ent).Error

  result = ent

  if err != nil {
    return err
  }
  return nil
}

And calling this method sth like:

func List(){
  var entityList []MyEntity
  find(entityList, 1, 10)
}

I think, I cannot pass any interface reference into Gorm.db.Find() method Is there any other way to succeed?





Aucun commentaire:

Enregistrer un commentaire