guesstimate/internal/orm/service.go

48 lines
984 B
Go
Raw Normal View History

2020-08-08 15:04:59 +02:00
package orm
import (
"github.com/jinzhu/gorm"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/service"
)
const ServiceName service.Name = "orm"
type Service struct {
db *gorm.DB
migration *MigrationManager
}
func (s *Service) DB() *gorm.DB {
return s.db
}
func (s *Service) Migration() *MigrationManager {
return s.migration
}
// From retrieves the orm service in the given container.
func From(container *service.Container) (*Service, error) {
service, err := container.Service(ServiceName)
if err != nil {
return nil, errors.Wrapf(err, "error while retrieving '%s' service", ServiceName)
}
srv, ok := service.(*Service)
if !ok {
return nil, errors.Errorf("retrieved service is not a valid '%s' service", ServiceName)
}
return srv, nil
}
// Must retrieves the orm pool service in the given container or panic otherwise.
func Must(container *service.Container) *Service {
srv, err := From(container)
if err != nil {
panic(err)
}
return srv
}