54 lines
1.8 KiB
Go
54 lines
1.8 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/gochat/gochat/internal/model"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// CopilotMessageRepo provides data access for CopilotMessage.
|
|
type CopilotMessageRepo struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func NewCopilotMessageRepo(db *gorm.DB) *CopilotMessageRepo {
|
|
return &CopilotMessageRepo{db: db}
|
|
}
|
|
|
|
func (r *CopilotMessageRepo) DB() *gorm.DB {
|
|
return r.db
|
|
}
|
|
|
|
func (r *CopilotMessageRepo) Create(ctx context.Context, msg *model.CopilotMessage) error {
|
|
return r.db.WithContext(ctx).Create(msg).Error
|
|
}
|
|
|
|
func (r *CopilotMessageRepo) GetByID(ctx context.Context, id uint) (*model.CopilotMessage, error) {
|
|
var msg model.CopilotMessage
|
|
if err := r.db.WithContext(ctx).Preload("CopilotThread.User").Preload("CopilotThread.Assistant").First(&msg, id).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
return &msg, nil
|
|
}
|
|
|
|
func (r *CopilotMessageRepo) FindByThreadID(ctx context.Context, threadID uint, offset, limit int) ([]model.CopilotMessage, int64, error) {
|
|
var msgs []model.CopilotMessage
|
|
var count int64
|
|
db := r.db.WithContext(ctx).Model(&model.CopilotMessage{}).Where("copilot_thread_id = ?", threadID)
|
|
db.Count(&count)
|
|
if err := db.Preload("CopilotThread.User").Preload("CopilotThread.Assistant").Offset(offset).Limit(limit).Order("created_at ASC").Find(&msgs).Error; err != nil {
|
|
return nil, 0, err
|
|
}
|
|
return msgs, count, nil
|
|
}
|
|
|
|
// ListByThread is an alias for FindByThreadID for backward compatibility.
|
|
func (r *CopilotMessageRepo) ListByThread(ctx context.Context, threadID uint, offset, limit int) ([]model.CopilotMessage, int64, error) {
|
|
return r.FindByThreadID(ctx, threadID, offset, limit)
|
|
}
|
|
|
|
func (r *CopilotMessageRepo) DeleteByThread(ctx context.Context, threadID uint) error {
|
|
return r.db.WithContext(ctx).Where("copilot_thread_id = ?", threadID).Delete(&model.CopilotMessage{}).Error
|
|
}
|