project_repository.go 2.5 KB
package repository

import (
	"fmt"
	"github.com/astaxie/beego/orm"
	"openapi/pkg/domain"
	"openapi/pkg/infrastructure/bgorm/models"
	. "openapi/pkg/infrastructure/utils"
)

type ProjectRepository struct{}

func (repository *ProjectRepository) Save(dm *domain.Project) (*domain.Project, error) {
	var (
		err error
		m   = &models.Project{}
	)
	if err = GobModelTransform(m, dm); err != nil {
		return nil, err
	}
	if dm.Identify() == nil {
		if _, err = models.AddProject(m); err != nil {
			return nil, err
		}
		return dm, nil
	}
	if err = models.UpdateProjectById(m); err != nil {
		return nil, err
	}
	return dm, nil
}

func (repository *ProjectRepository) Remove(Project *domain.Project) (*domain.Project, error) {
	if err := models.DeleteProject(Project.Id); err != nil {
		return nil, err
	}
	return nil, nil
}

func (repository *ProjectRepository) FindOne(queryOptions map[string]interface{}) (*domain.Project, error) {
	m := new(models.Project)
	//key := queryOptions["project_slave_key"].(string)
	//if v, ok := Cache.Load(key); ok {
	//	return repository.transformPgModelToDomainModel(v.(*models.Project))
	//}

	qb, _ := orm.NewQueryBuilder("mysql")
	qb.Select("*")
	qb.From("project")
	if v, ok := queryOptions["project_slave_key"]; ok {
		qb.Where(fmt.Sprintf("project_slave_key = '%v'", v))
	}
	sql := qb.String()
	o := orm.NewOrm()
	if err := o.Raw(sql).QueryRow(m); err != nil {
		return nil, err
	}
	//Cache.Store(key, m)
	return repository.transformPgModelToDomainModel(m)
}

func (repository *ProjectRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.Project, error) {
	var models []*models.Project
	dms := make([]*domain.Project, 0)
	qb, _ := orm.NewQueryBuilder("mysql")
	qb.From("project")
	if v, ok := queryOptions["project_key"]; ok {
		qb.Where(fmt.Sprintf("project_key = '%v'", v))
	}
	sql := qb.String()
	o := orm.NewOrm()
	if _, err := o.Raw(sql).QueryRows(models); err != nil {
		return 0, nil, err
	}
	for _, m := range models {
		if dm, err := repository.transformPgModelToDomainModel(m); err != nil {
			return 0, nil, err
		} else {
			dms = append(dms, dm)
		}
	}
	return int64(len(dms)), dms, nil
}

func (repository *ProjectRepository) transformPgModelToDomainModel(model *models.Project) (*domain.Project, error) {
	return &domain.Project{
		Id:               model.Id,
		ProjectName:      model.ProjectName,
		ProjectSlaveKey:  model.ProjectSlaveKey,
		ProjectMasterKey: model.ProjectMasterKey,
	}, nil
}

func NewProjectRepository() (*ProjectRepository, error) {
	return &ProjectRepository{}, nil
}