daddy/internal/model/event_repository.go

74 lines
1.4 KiB
Go
Raw Permalink Normal View History

package model
import (
"context"
"github.com/jinzhu/gorm"
errs "github.com/pkg/errors"
)
type EventRepository struct {
db *gorm.DB
}
func (r *EventRepository) Add(ctx context.Context, user *User, eventType EventType, obj EventObject) (*Event, error) {
evt := &Event{
Type: eventType,
User: user,
ObjectID: obj.ObjectID(),
ObjectType: obj.ObjectType(),
}
if err := r.db.Save(&evt).Error; err != nil {
return nil, errs.WithStack(err)
}
return evt, nil
}
func (r *EventRepository) Search(ctx context.Context, filter *EventFilter) ([]*Event, error) {
query := r.db.Model(&Event{}).Preload("User")
if filter == nil {
filter = &EventFilter{}
}
if filter.ObjectID != nil {
query = query.Where("object_id = ?", filter.ObjectID)
}
if filter.ObjectType != nil {
query = query.Where("object_type = ?", filter.ObjectType)
}
if filter.UserID != nil {
query = query.Where("user_id = ?", filter.UserID)
}
if filter.Type != nil {
query = query.Where("type = ?", filter.Type)
}
if filter.From != nil {
query = query.Where("created_at >= ?", filter.From)
}
if filter.To != nil {
query = query.Where("created_at <= ?", filter.To)
}
query = query.Order("created_at DESC")
events := make([]*Event, 0)
if err := query.Find(&events).Error; err != nil {
return nil, errs.WithStack(err)
}
return events, nil
}
func NewEventRepository(db *gorm.DB) *EventRepository {
return &EventRepository{db}
}