Refactoring validation to belong to model

This commit is contained in:
2026-03-19 00:44:37 +00:00
parent a33cedf09e
commit de6c9d6ae5
6 changed files with 224 additions and 57 deletions

View File

@@ -1,35 +0,0 @@
package repository
import (
"fmt"
"git.hrafn.xyz/aether/notes/internal/models"
)
type EmptyContent struct {}
type EmptyTitle struct {}
type NoOP struct {}
type EmptyUpdate struct{}
type TitleOverflow struct {
length int
}
func (e *EmptyContent) Error() string {
return "content cannot be empty"
}
func (e *EmptyTitle) Error() string {
return "title cannot be empty"
}
func (e *NoOP) Error() string {
return "no operation required"
}
func (e *EmptyUpdate) Error() string {
return "update cannot be empty"
}
func (e *TitleOverflow) Error() string {
return fmt.Sprintf("title max length %d, %d provided", models.NoteTitleMaxLength, e.length)
}

View File

@@ -29,7 +29,7 @@ func (r *NoteRepository) CreateNote(ctx context.Context, title string, content s
Content: content,
LastUpdate: time.Now(),
}
if err := isNoteVaid(note); err != nil {
if err := note.Validate(); err != nil {
return models.Note{}, err
}
return r.store.SaveNote(ctx, note)
@@ -48,7 +48,7 @@ func (r *NoteRepository) ListNotes(ctx context.Context) ([]models.Note, error) {
// UpdateNote updates the content of an existing note.
func (r *NoteRepository) UpdateNote(ctx context.Context, id int, update NoteUpdate) (models.Note, error) {
if update.Content == "" && update.Title == "" {
return models.Note{}, &EmptyUpdate{}
return models.Note{}, &ErrEmptyUpdate{}
}
note, err := r.store.GetNoteByID(ctx, id)
if err != nil {
@@ -56,7 +56,7 @@ func (r *NoteRepository) UpdateNote(ctx context.Context, id int, update NoteUpda
}
if update.Content == note.Content && update.Title == note.Title {
return models.Note{}, &NoOP{}
return models.Note{}, &ErrNoOP{}
}
if update.Content != "" {
@@ -65,8 +65,8 @@ func (r *NoteRepository) UpdateNote(ctx context.Context, id int, update NoteUpda
if update.Title != "" {
note.Title = update.Title
}
if err := isNoteVaid(note); err != nil {
if err := note.Validate(); err != nil {
return models.Note{}, err
}
@@ -78,20 +78,3 @@ func (r *NoteRepository) UpdateNote(ctx context.Context, id int, update NoteUpda
func (r *NoteRepository) DeleteNote(ctx context.Context, id int) error {
return r.store.DeleteNoteByID(ctx, id)
}
func isNoteVaid(note models.Note) error {
if note.Title == "" {
return &EmptyTitle{}
}
if note.Content == "" {
return &EmptyContent{}
}
if titleLen := len(note.Title); titleLen > models.NoteTitleMaxLength {
return &TitleOverflow{
length: titleLen,
}
}
return nil
}

View File

@@ -0,0 +1,12 @@
package repository
type ErrNoOP struct{}
type ErrEmptyUpdate struct{}
func (e *ErrNoOP) Error() string {
return "no operation required"
}
func (e *ErrEmptyUpdate) Error() string {
return "update cannot be empty"
}