94 lines
2.1 KiB
Go
94 lines
2.1 KiB
Go
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"
|
|
)
|
|
|
|
func CreateTag(ctx context.Context, db *gorm.DB, tag *models.Tag) error {
|
|
|
|
if tag == nil {
|
|
return &errors2.EntityValidationFailed{Reason: "Tag is nil"}
|
|
}
|
|
|
|
result := db.WithContext(ctx).Where(tag).Create(tag)
|
|
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{
|
|
"tag_name": tag.Name,
|
|
"tag_type": tag.Type,
|
|
}).Trace("database: created tag node")
|
|
|
|
return nil
|
|
}
|
|
|
|
func CreateTagAndReferenceToPost(ctx context.Context, db *gorm.DB, anthrovePostID models.AnthrovePostID, tag *models.Tag) error {
|
|
|
|
if anthrovePostID == "" {
|
|
return &errors2.EntityValidationFailed{Reason: "anthrovePostID cannot be empty"}
|
|
}
|
|
|
|
if len(anthrovePostID) != 25 {
|
|
return &errors2.EntityValidationFailed{Reason: "anthrovePostID needs to be 25 characters long"}
|
|
}
|
|
|
|
if tag == nil {
|
|
return &errors2.EntityValidationFailed{Reason: "Tag is nil"}
|
|
}
|
|
|
|
pgPost := models.Post{
|
|
BaseModel: models.BaseModel[models.AnthrovePostID]{
|
|
ID: anthrovePostID,
|
|
},
|
|
}
|
|
|
|
err := db.WithContext(ctx).Model(&pgPost).Association("Tags").Append(tag)
|
|
if err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return &errors2.NoDataFound{}
|
|
}
|
|
return errors.Join(err, &errors2.NoRelationCreated{})
|
|
}
|
|
|
|
log.WithFields(log.Fields{
|
|
"anthrove_post_id": anthrovePostID,
|
|
"tag_name": tag.Name,
|
|
"tag_type": tag.Type,
|
|
}).Trace("database: created tag node")
|
|
|
|
return nil
|
|
}
|
|
|
|
func GetTags(ctx context.Context, db *gorm.DB) ([]models.Tag, error) {
|
|
var tags []models.Tag
|
|
|
|
result := db.WithContext(ctx).Find(&tags)
|
|
|
|
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": len(tags),
|
|
}).Trace("database: got tags")
|
|
|
|
return tags, nil
|
|
}
|