Skip to content

Instantly share code, notes, and snippets.

@kamal-kambe
Created July 31, 2019 14:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamal-kambe/e372a5333dd8ff32a8d4c318c5b05dfb to your computer and use it in GitHub Desktop.
Save kamal-kambe/e372a5333dd8ff32a8d4c318c5b05dfb to your computer and use it in GitHub Desktop.
package sql
import (
"encoding/json"
"fmt"
"reflect"
"github.com/jinzhu/gorm"
"sample-app/model"
"sample-app/service"
"sample-app/util"
)
type baseRepository struct {
*gorm.DB
}
func NewBaseRepository(db *gorm.DB) service.BaseRepository {
return &baseRepository{db}
}
func (br *baseRepository) GetRows(models []string) json.RawMessage {
data := map[string]interface{}{}
for _, modelName := range models {
modelSlice, ok := util.NewInstanceSlice(modelName)
if !ok {
panic("Model is not registered")
}
rows := reflect.New(modelSlice.Type()).Interface()
if err := br.Model(rows).Find(rows).Error; err != nil {
fmt.Printf("Error while getting data for model: %s and the error is: %v", modelName, err)
}
data[modelName] = rows
}
jsonData, _ := json.Marshal(data)
return jsonData
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment