1
0
mirror of https://github.com/muety/wakapi.git synced 2023-08-10 21:12:56 +03:00
wakapi/services/heartbeat.go

56 lines
1.3 KiB
Go
Raw Normal View History

2019-05-05 23:36:49 +03:00
package services
import (
"time"
2019-05-05 23:36:49 +03:00
2019-05-11 18:49:56 +03:00
"github.com/jinzhu/gorm"
2019-05-05 23:36:49 +03:00
"github.com/n1try/wakapi/models"
2019-05-11 18:49:56 +03:00
gormbulk "github.com/t-tiger/gorm-bulk-insert"
2019-05-05 23:36:49 +03:00
)
2019-05-06 01:40:41 +03:00
const TableHeartbeat = "heartbeat"
2019-05-05 23:36:49 +03:00
type HeartbeatService struct {
2019-05-21 18:16:46 +03:00
Config *models.Config
2019-05-16 23:53:03 +03:00
Db *gorm.DB
2019-05-05 23:36:49 +03:00
}
func (srv *HeartbeatService) InsertBatch(heartbeats []*models.Heartbeat) error {
2019-05-11 18:49:56 +03:00
var batch []interface{}
for _, h := range heartbeats {
batch = append(batch, *h)
2019-05-05 23:36:49 +03:00
}
2019-05-11 18:49:56 +03:00
if err := gormbulk.BulkInsert(srv.Db, batch, 3000); err != nil {
2019-05-05 23:36:49 +03:00
return err
}
return nil
}
func (srv *HeartbeatService) GetAllWithin(from, to time.Time, user *models.User) ([]*models.Heartbeat, error) {
var heartbeats []*models.Heartbeat
2019-05-11 18:49:56 +03:00
if err := srv.Db.
Where(&models.Heartbeat{UserID: user.ID}).
Where("time >= ?", from).
Where("time <= ?", to).
2019-05-20 20:46:41 +03:00
Order("time asc").
Find(&heartbeats).Error; err != nil {
2019-05-11 18:49:56 +03:00
return nil, err
}
return heartbeats, nil
}
// Will return *models.Heartbeat object with only user_id and time fields filled
func (srv *HeartbeatService) GetFirstUserHeartbeats(userIds []string) ([]*models.Heartbeat, error) {
var heartbeats []*models.Heartbeat
if err := srv.Db.
Table("heartbeats").
Select("user_id, min(time) as time").
Where("user_id IN (?)", userIds).
Group("user_id").
Scan(&heartbeats).Error; err != nil {
return nil, err
}
return heartbeats, nil
}