This repository has been archived on 2024-07-22. You can view files and clone it, but cannot push or open issues or pull requests.
otter-space-sdk/internal/postgres/source.go

85 lines
2.3 KiB
Go
Raw Normal View History

package postgres
import (
"context"
"errors"
errors2 "git.dragse.it/anthrove/otter-space-sdk/pkg/errors"
"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 &errors2.EntityValidationFailed{Reason: "Domain is required"}
}
result := db.WithContext(ctx).Where(models.Source{Domain: anthroveSource.Domain}).FirstOrCreate(anthroveSource)
if result.Error != nil {
if errors.Is(result.Error, gorm.ErrDuplicatedKey) {
return &errors2.EntityAlreadyExists{}
}
return result.Error
}
if result.RowsAffected == 0 {
return &errors2.NoDataWritten{}
}
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 {
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, &errors2.NoDataFound{}
} // TODO really...? i don't think this error handling should be here..? / not possible
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, &errors2.EntityValidationFailed{Reason: "AnthroveSourceDomain is not set"}
}
result := db.WithContext(ctx).Where("domain = ?", sourceDomain).First(&sources)
if result.Error != nil {
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, &errors2.NoDataFound{}
}
return nil, result.Error
}
log.WithFields(log.Fields{
"tag_amount": result.RowsAffected,
}).Trace("database: get all source nodes")
return &sources, nil
}