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

67 lines
1.7 KiB
Go
Raw Normal View History

2024-06-14 11:29:53 +00:00
package postgres
import (
"context"
"errors"
"fmt"
2024-06-14 11:29:53 +00:00
"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 {
err := db.WithContext(ctx).Create(&anthrovePost).Error
2024-06-14 11:29:53 +00:00
if err != nil {
return err
}
log.WithFields(log.Fields{
"anthrove_post_id": anthrovePost.ID,
"anthrove_post_rating": anthrovePost.Rating,
2024-06-14 11:29:53 +00:00
}).Trace("database: created anthrove post")
return nil
}
func GetPostByAnthroveID(ctx context.Context, db *gorm.DB, anthrovePostID string) (*models.Post, error) {
if anthrovePostID == "" {
return nil, fmt.Errorf("anthrovePostID is required")
}
var post models.Post
err := db.WithContext(ctx).First(&post, "id = ?", anthrovePostID).Error
if err != nil {
return nil, err
}
return &post, nil
}
func GetPostBySourceURL(ctx context.Context, db *gorm.DB, sourceURL string) (*models.Post, error) {
var post models.Post
err := 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).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
return nil, err
}
return &post, nil
}
func GetPostBySourceID(ctx context.Context, db *gorm.DB, sourceID string) (*models.Post, error) {
var post models.Post
err := 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).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
return nil, err
}
return &post, nil
}