feat: update news
This commit is contained in:
@@ -13,6 +13,7 @@ type News interface {
|
||||
GetAll() ([]newsdomain.News, error)
|
||||
GetBySlug(string) (*newsdomain.News, error)
|
||||
Create(newsdomain.News) error
|
||||
Update(newsdomain.News) error
|
||||
Delete(string) error
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package newsrepository
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
newsdomain "legalgo-BE-go/internal/domain/news"
|
||||
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
func (a *accessor) Update(spec newsdomain.News) error {
|
||||
tx := a.db.Begin()
|
||||
if err := tx.Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "id"}},
|
||||
DoUpdates: clause.AssignmentColumns([]string{
|
||||
"title",
|
||||
"content",
|
||||
"featured_image",
|
||||
"is_premium",
|
||||
"slug",
|
||||
"author_id",
|
||||
"live_at",
|
||||
"updated_at",
|
||||
}),
|
||||
}).Select(
|
||||
"title",
|
||||
"content",
|
||||
"featured_image",
|
||||
"is_premium",
|
||||
"slug",
|
||||
"author_id",
|
||||
"live_at",
|
||||
"updated_at",
|
||||
).Save(&spec).Error; err != nil {
|
||||
tx.Rollback()
|
||||
return fmt.Errorf("failed to update news: %v", err)
|
||||
}
|
||||
if len(spec.Tags) < 1 {
|
||||
if err := tx.Model(&spec).Association("Tags").Clear(); err != nil {
|
||||
tx.Rollback()
|
||||
return fmt.Errorf("failed to clear tags: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if len(spec.Categories) < 1 {
|
||||
if err := tx.Model(&spec).Association("Categories").Clear(); err != nil {
|
||||
tx.Rollback()
|
||||
return fmt.Errorf("failed to clear categories: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Model(&spec).Association("Tags").Append(spec.Tags); err != nil {
|
||||
tx.Rollback()
|
||||
return fmt.Errorf("failed to add tags: %v", err)
|
||||
}
|
||||
|
||||
if err := tx.Model(&spec).Association("Categories").Append(spec.Categories); err != nil {
|
||||
tx.Rollback()
|
||||
return fmt.Errorf("failed to add categories: %v", err)
|
||||
}
|
||||
|
||||
if err := tx.Commit().Error; err != nil {
|
||||
return fmt.Errorf("failed to commit transaction: %v", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user