otter-space-sdk/internal/postgres/source.go
2024-06-23 22:35:46 +02:00

71 lines
1.7 KiB
Go

package postgres
import (
"context"
"fmt"
"git.dragse.it/anthrove/otter-space-sdk/pkg/models"
log "github.com/sirupsen/logrus"
"gorm.io/gorm"
)
// CreateSource creates a pgModels.Source
func CreateSource(ctx context.Context, db *gorm.DB, anthroveSource *models.Source) error {
if anthroveSource.Domain == "" {
return fmt.Errorf("anthroveSource domain is required")
}
result := db.WithContext(ctx).Where(models.Source{Domain: anthroveSource.Domain}).FirstOrCreate(anthroveSource)
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
}
// GetAllSource returns a list of all pgModels.Source
func GetAllSource(ctx context.Context, db *gorm.DB) ([]models.Source, error) {
var sources []models.Source
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
}
// GetSourceByDomain returns the first source it finds based on the domain
func GetSourceByDomain(ctx context.Context, db *gorm.DB, sourceDomain models.AnthroveSourceDomain) (*models.Source, error) {
var sources models.Source
if sourceDomain == "" {
return nil, fmt.Errorf("domain is required")
}
result := db.WithContext(ctx).Where("domain = ?", sourceDomain).First(&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
}