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/post.go
SoXX 6e3edfc1fa fix(errors): renamed error package
Signed-off-by: SoXX <soxx@fenpa.ws>
2024-06-26 10:02:54 +02:00

99 lines
2.7 KiB
Go

package postgres
import (
"context"
"errors"
otterError "git.dragse.it/anthrove/otter-space-sdk/pkg/error"
"git.dragse.it/anthrove/otter-space-sdk/pkg/models"
log "github.com/sirupsen/logrus"
"gorm.io/gorm"
)
func CreatePost(ctx context.Context, db *gorm.DB, anthrovePost *models.Post) error {
if anthrovePost == nil {
return &otterError.EntityValidationFailed{Reason: "anthrovePost is nil"}
}
result := db.WithContext(ctx).Create(&anthrovePost)
if result.Error != nil {
if errors.Is(result.Error, gorm.ErrDuplicatedKey) {
return &otterError.EntityAlreadyExists{}
}
return result.Error
}
if result.RowsAffected == 0 {
return &otterError.NoDataWritten{}
}
log.WithFields(log.Fields{
"anthrove_post_id": anthrovePost.ID,
"anthrove_post_rating": anthrovePost.Rating,
}).Trace("database: created anthrove post")
return nil
}
func GetPostByAnthroveID(ctx context.Context, db *gorm.DB, anthrovePostID models.AnthrovePostID) (*models.Post, error) {
if anthrovePostID == "" {
return nil, &otterError.EntityValidationFailed{Reason: "anthrovePostID is not set"}
}
if len(anthrovePostID) != 25 {
return nil, &otterError.EntityValidationFailed{Reason: "anthrovePostID needs to be 25 characters long"}
}
var post models.Post
result := db.WithContext(ctx).First(&post, "id = ?", anthrovePostID)
if result.Error != nil {
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, &otterError.NoDataFound{}
}
return nil, result.Error
}
return &post, nil
}
func GetPostByURL(ctx context.Context, db *gorm.DB, sourceURL string) (*models.Post, error) {
if sourceURL == "" {
return nil, &otterError.EntityValidationFailed{Reason: "sourceURL is not set"}
}
var post models.Post
result := db.WithContext(ctx).Raw(`SELECT p.id AS id, p.rating as rating FROM "Post" AS p INNER JOIN "PostReference" AS pr ON p.id = pr.post_id AND pr.url = $1 LIMIT 1`, sourceURL).First(&post)
if result.Error != nil {
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, &otterError.NoDataFound{}
}
return nil, result.Error
}
return &post, nil
}
func GetPostBySourceID(ctx context.Context, db *gorm.DB, sourceID models.AnthroveSourceID) (*models.Post, error) {
if sourceID == "" {
return nil, &otterError.EntityValidationFailed{Reason: "sourceID is not set"}
}
var post models.Post
result := db.WithContext(ctx).Raw(`SELECT p.id AS id, p.rating as rating FROM "Post" AS p INNER JOIN "PostReference" AS pr ON p.id = pr.post_id AND pr.source_id = $1 LIMIT 1`, sourceID).First(&post)
if result.Error != nil {
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, &otterError.NoDataFound{}
}
return nil, result.Error
}
return &post, nil
}