Files
RenewCMS/internal/infrastructure/useCases/UpdateEntry.go
T

50 lines
1.3 KiB
Go

package useCases
import (
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
"time"
)
type UpdateEntryUseCase struct {
contentTypes contenttype.Repository
entries entry.Repository
now func() time.Time
}
type UpdateEntryCommand struct {
ContentTypeKey string
ID uint32
Data map[string]any
UserID uint32
}
func NewUpdateEntryUseCase(contentTypes contenttype.Repository, entries entry.Repository, now func() time.Time) *UpdateEntryUseCase {
return &UpdateEntryUseCase{contentTypes, entries, now}
}
func (u *UpdateEntryUseCase) Update(command UpdateEntryCommand) (TypedEntry, error) {
owner, err := u.contentTypes.GetByKey(command.ContentTypeKey)
if err != nil {
return TypedEntry{}, err
}
current, err := u.entries.Get(owner.ID, command.ID)
if err != nil {
return TypedEntry{}, err
}
if err := entry.Validate(owner.Fields, command.Data); err != nil {
return TypedEntry{}, err
}
if err := ensureUnique(u.entries, owner, command.Data, current.ID); err != nil {
return TypedEntry{}, err
}
current.Data = command.Data
current.UpdatedBy = command.UserID
current.UpdatedAt = u.now()
stored, err := u.entries.Update(current)
if err != nil {
return TypedEntry{}, err
}
return typedEntry(owner, stored), nil
}