push_device_info_repository.go 2.1 KB
package repository

import (
	"github.com/astaxie/beego/orm"
	"openapi/pkg/domain"
	"openapi/pkg/infrastructure/bgorm/model"
	"strings"
	"time"
)

type PushDeviceRepository struct {
}

func (repository *PushDeviceRepository) Save(device *domain.UpdateDeviceRequest) error {
	o := orm.NewOrm()

	m := &models.PushDeviceInfo{
		Uid:         device.Muid,
		ClientId:    strings.TrimSpace(device.ClientId),
		DeviceToken: strings.TrimSpace(device.DeviceToken),
		CreateAt:    time.Now(),
		UpdateAt:    time.Now(),
	}
	_, err := o.Insert(m)
	return err
}

func (repository *PushDeviceRepository) FindOne(queryOptions map[string]interface{}) (*domain.Device, error) {
	o := orm.NewOrm()
	model := new(models.PushDeviceInfo)
	qs := o.QueryTable(model.TableName()).Filter("uid", queryOptions["uid"])
	err := qs.One(model)
	if err != nil {
		err = domain.ERR_DB_NOT_FOUND
		return nil, err
	}
	return repository.transformBgormModelToDomainModel(model)
}

func (repository *PushDeviceRepository) Find(queryOptions map[string]interface{}) (rsp []*domain.Device, err error) {
	o := orm.NewOrm()
	model := new(models.PushDeviceInfo)
	var ms []*models.PushDeviceInfo
	qs := o.QueryTable(model.TableName()).Filter("uid__in", queryOptions["receivers"])
	qs.All(&ms)
	if len(ms) == 0 {
		return
	}
	for i := range ms {
		v, _ := repository.transformBgormModelToDomainModel(ms[i])
		rsp = append(rsp, v)
	}
	return
}

func (repository *PushDeviceRepository) UpdateDevice(uid int64, clientId, deviceToken string) error {
	o := orm.NewOrm()
	_, err := o.Raw("UPDATE push_device_info SET client_id=?,device_token = ?,update_at=now() where uid=?", clientId, deviceToken, uid).Exec()
	if err != nil {
		return err
	}
	return nil
}

func (repository *PushDeviceRepository) transformBgormModelToDomainModel(model *models.PushDeviceInfo) (*domain.Device, error) {
	return &domain.Device{
		Uid:         model.Uid,
		ClientId:    model.ClientId,
		DeviceToken: model.DeviceToken,
	}, nil
}

func NewPushDeviceRepository(transactionContext interface{}) (*PushDeviceRepository, error) {
	if transactionContext == nil {
		return &PushDeviceRepository{}, nil
	} else {
		return &PushDeviceRepository{}, nil
	}
}