2024-06-03 20:14:50 +00:00
|
|
|
package postgres
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-06-19 22:13:39 +00:00
|
|
|
"fmt"
|
2024-06-22 20:06:36 +00:00
|
|
|
"git.dragse.it/anthrove/otter-space-sdk/pkg/models"
|
2024-06-04 13:16:37 +00:00
|
|
|
|
2024-06-03 20:14:50 +00:00
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
)
|
|
|
|
|
2024-06-23 19:23:38 +00:00
|
|
|
// CreateSource creates a pgModels.Source
|
|
|
|
func CreateSource(ctx context.Context, db *gorm.DB, anthroveSource *models.Source) error {
|
2024-06-04 13:16:37 +00:00
|
|
|
|
2024-06-19 22:13:39 +00:00
|
|
|
if anthroveSource.Domain == "" {
|
|
|
|
return fmt.Errorf("anthroveSource domain is required")
|
|
|
|
}
|
|
|
|
|
2024-06-22 20:06:36 +00:00
|
|
|
result := db.WithContext(ctx).Where(models.Source{Domain: anthroveSource.Domain}).FirstOrCreate(anthroveSource)
|
2024-06-04 13:16:37 +00:00
|
|
|
|
|
|
|
if result.Error != nil {
|
|
|
|
return result.Error
|
|
|
|
}
|
|
|
|
|
|
|
|
log.WithFields(log.Fields{
|
|
|
|
"node_source_url": anthroveSource.Domain,
|
|
|
|
"node_source_displayName": anthroveSource.DisplayName,
|
|
|
|
"node_source_icon": anthroveSource.Icon,
|
|
|
|
}).Trace("database: created source node")
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-06-23 19:23:38 +00:00
|
|
|
// GetAllSource returns a list of all pgModels.Source
|
|
|
|
func GetAllSource(ctx context.Context, db *gorm.DB) ([]models.Source, error) {
|
2024-06-22 20:06:36 +00:00
|
|
|
var sources []models.Source
|
2024-06-03 20:14:50 +00:00
|
|
|
|
|
|
|
result := db.WithContext(ctx).Find(&sources)
|
|
|
|
|
|
|
|
if result.Error != nil {
|
|
|
|
return nil, result.Error
|
|
|
|
}
|
|
|
|
|
|
|
|
log.WithFields(log.Fields{
|
|
|
|
"tag_amount": result.RowsAffected,
|
|
|
|
}).Trace("database: get all source nodes")
|
|
|
|
|
|
|
|
return sources, nil
|
|
|
|
}
|
2024-06-04 13:16:37 +00:00
|
|
|
|
2024-06-23 19:23:38 +00:00
|
|
|
// GetSourceByURL returns the first source it finds based on the domain
|
|
|
|
func GetSourceByURL(ctx context.Context, db *gorm.DB, domain string) (*models.Source, error) {
|
2024-06-22 20:06:36 +00:00
|
|
|
var sources models.Source
|
2024-06-04 13:16:37 +00:00
|
|
|
|
2024-06-19 22:13:39 +00:00
|
|
|
if domain == "" {
|
|
|
|
return nil, fmt.Errorf("domain is required")
|
|
|
|
}
|
2024-06-04 13:16:37 +00:00
|
|
|
|
|
|
|
result := db.WithContext(ctx).Where("domain = ?", domain).First(&sources)
|
|
|
|
|
|
|
|
if result.Error != nil {
|
|
|
|
return nil, result.Error
|
|
|
|
}
|
|
|
|
|
|
|
|
log.WithFields(log.Fields{
|
|
|
|
"tag_amount": result.RowsAffected,
|
|
|
|
}).Trace("database: get all source nodes")
|
|
|
|
|
2024-06-19 22:13:39 +00:00
|
|
|
return &sources, nil
|
2024-06-04 13:16:37 +00:00
|
|
|
}
|