73 lines
1.4 KiB
Go
73 lines
1.4 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"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 {
|
|
|
|
resultTag := db.WithContext(ctx).Where(tag).Create(tag)
|
|
|
|
if resultTag.Error != nil {
|
|
return resultTag.Error
|
|
}
|
|
|
|
log.WithFields(log.Fields{
|
|
"tag_name": tag.Name,
|
|
"tag_type": tag.Type,
|
|
}).Trace("database: created tag node")
|
|
|
|
return nil
|
|
}
|
|
|
|
func CreateTagNodeWitRelation(ctx context.Context, db *gorm.DB, PostID models.AnthrovePostID, tag *models.Tag) error {
|
|
|
|
if PostID == "" {
|
|
return fmt.Errorf("PostID is empty")
|
|
}
|
|
|
|
resultTag := db.WithContext(ctx).Where(tag).FirstOrCreate(tag)
|
|
|
|
if resultTag.Error != nil {
|
|
return resultTag.Error
|
|
}
|
|
|
|
pgPost := models.Post{
|
|
BaseModel: models.BaseModel{
|
|
ID: string(PostID),
|
|
},
|
|
}
|
|
|
|
err := db.WithContext(ctx).Model(&pgPost).Association("Tags").Append(tag)
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
log.WithFields(log.Fields{
|
|
"anthrove_post_id": PostID,
|
|
"tag_name": tag.Name,
|
|
"tag_type": tag.Type,
|
|
}).Trace("database: created tag node")
|
|
|
|
return nil
|
|
}
|
|
|
|
func GetTags(ctx context.Context, db *gorm.DB) ([]models.TagsWithFrequency, error) {
|
|
var tags []models.Tag
|
|
result := db.WithContext(ctx).Find(&tags)
|
|
if result.Error != nil {
|
|
return nil, result.Error
|
|
}
|
|
|
|
log.WithFields(log.Fields{
|
|
"tag_amount": len(tags),
|
|
}).Trace("database: got tags")
|
|
|
|
return tags, nil
|
|
}
|