70 lines
2.3 KiB
Go
70 lines
2.3 KiB
Go
package useCases
|
|
|
|
import (
|
|
"RenewCMS/internal/domain/article"
|
|
"RenewCMS/internal/domain/audit"
|
|
"context"
|
|
)
|
|
|
|
type UpdateArticleUseCase struct {
|
|
articleRepository article.Repository
|
|
bodyRenderer article.BodyRenderer
|
|
recorder audit.Recorder
|
|
}
|
|
|
|
func NewUpdateArticleUseCase(articleRepository article.Repository, bodyRenderer article.BodyRenderer, recorder audit.Recorder) *UpdateArticleUseCase {
|
|
return &UpdateArticleUseCase{articleRepository, bodyRenderer, recorder}
|
|
}
|
|
|
|
func (g *UpdateArticleUseCase) UpdateBody(ctx context.Context, id uint32, body string, format article.BodyFormat) (article.Article, error) {
|
|
before, err := g.articleRepository.Get(id)
|
|
if err != nil {
|
|
return article.Article{}, err
|
|
}
|
|
updated, err := g.articleRepository.UpdateBody(id, body)
|
|
if err != nil {
|
|
g.recordFailure(ctx, audit.ActionArticleEdit, before, err)
|
|
return article.Article{}, err
|
|
}
|
|
g.recordChange(ctx, audit.ActionArticleEdit, before, updated)
|
|
return renderArticle(g.bodyRenderer, updated, format)
|
|
}
|
|
|
|
func (g *UpdateArticleUseCase) UpdateIsOnline(ctx context.Context, id uint32, isOnline bool, format article.BodyFormat) (article.Article, error) {
|
|
before, err := g.articleRepository.Get(id)
|
|
if err != nil {
|
|
return article.Article{}, err
|
|
}
|
|
updated, err := g.articleRepository.UpdateIsOnline(id, isOnline)
|
|
if err != nil {
|
|
g.recordFailure(ctx, publishAction(isOnline), before, err)
|
|
return article.Article{}, err
|
|
}
|
|
g.recordChange(ctx, publishAction(isOnline), before, updated)
|
|
return renderArticle(g.bodyRenderer, updated, format)
|
|
}
|
|
|
|
func publishAction(isOnline bool) string {
|
|
if isOnline {
|
|
return audit.ActionArticlePublish
|
|
}
|
|
return audit.ActionArticleUnpublish
|
|
}
|
|
|
|
func (g *UpdateArticleUseCase) recordChange(ctx context.Context, action string, before article.Article, after article.Article) {
|
|
changes := audit.ArticleChanges(before, after)
|
|
if len(changes) == 0 {
|
|
return
|
|
}
|
|
event := audit.NewEvent(action, audit.CategoryArticles)
|
|
event.Target = articleTarget(after)
|
|
event.Changes = changes
|
|
g.recorder.Record(ctx, event)
|
|
}
|
|
|
|
func (g *UpdateArticleUseCase) recordFailure(ctx context.Context, action string, before article.Article, cause error) {
|
|
event := audit.NewEvent(action, audit.CategoryArticles)
|
|
event.Target = articleTarget(before)
|
|
recordFailure(ctx, g.recorder, event, cause)
|
|
}
|