ozon-task/internal/storage/db/database.go

63 lines
1.5 KiB
Go
Raw Normal View History

2024-06-24 23:34:10 +00:00
package db
import (
"git.obamna.ru/erius/ozon-task/graph/model"
"gorm.io/gorm"
)
type Database struct {
db *gorm.DB
}
func (s *Database) AddPost(input *model.PostInput) (*model.AddResult, error) {
post := model.PostFromInput(input)
err := s.db.Create(post).Error
return &model.AddResult{ItemID: &post.ID}, err
}
func (s *Database) AddComment(input *model.CommentInput) (*model.AddResult, error) {
comment := model.CommentFromInput(input)
if input.ParentPostID == nil {
// multiple operations performed in one transaction
err := s.db.Transaction(func(tx *gorm.DB) error {
var parent model.Comment
// find parent comment in db
err := s.db.First(&parent, *input.ParentCommentID).Error
if err != nil {
return err
}
// set new comment fields to reference parent post and comment
comment.ReplyTo = &parent
comment.PostID = parent.PostID
// insert comment
err = s.db.Create(comment).Error
if err != nil {
return err
}
// add new reply to parent and save
parent.Replies = append(parent.Replies, comment)
err = s.db.Save(parent).Error
if err != nil {
return err
}
return nil
})
if err != nil {
return nil, err
}
} else {
comment.PostID = *input.ParentPostID
err := s.db.Create(comment).Error
if err != nil {
return nil, err
}
}
return &model.AddResult{ItemID: &comment.ID}, nil
}
func (s Database) GetPosts() ([]*model.Post, error) {
var posts []*model.Post
err := s.db.Find(&posts).Error
return posts, err
}