97 lines
2.2 KiB
Go
97 lines
2.2 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"git.hrafn.xyz/aether/notes/internal/models"
|
|
)
|
|
|
|
// NoteRepository manages operations on notes using a data store.
|
|
type NoteRepository struct {
|
|
store NoteStore
|
|
}
|
|
|
|
type NoteUpdate struct {
|
|
Title string
|
|
Content string
|
|
}
|
|
|
|
// NewNoteRepository creates and returns a new NoteRepository instance.
|
|
func NewNoteRepository(store NoteStore) *NoteRepository {
|
|
return &NoteRepository{store: store}
|
|
}
|
|
|
|
// CreateNote creates a new note with the given content.
|
|
func (r *NoteRepository) CreateNote(ctx context.Context, title string, content string) (models.Note, error) {
|
|
note := models.Note{
|
|
Title: title,
|
|
Content: content,
|
|
LastUpdate: time.Now(),
|
|
}
|
|
if err := isNoteVaid(note); err != nil {
|
|
return models.Note{}, err
|
|
}
|
|
return r.store.SaveNote(ctx, note)
|
|
}
|
|
|
|
// GetNote retrieves a note by its ID.
|
|
func (r *NoteRepository) GetNote(ctx context.Context, id int) (models.Note, error) {
|
|
return r.store.GetNoteByID(ctx, id)
|
|
}
|
|
|
|
// ListNotes retrieves all notes.
|
|
func (r *NoteRepository) ListNotes(ctx context.Context) ([]models.Note, error) {
|
|
return r.store.GetAllNotes(ctx)
|
|
}
|
|
|
|
// 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{}
|
|
}
|
|
note, err := r.store.GetNoteByID(ctx, id)
|
|
if err != nil {
|
|
return models.Note{}, err
|
|
}
|
|
|
|
if update.Content == note.Content && update.Title == note.Title {
|
|
return models.Note{}, &NoOP{}
|
|
}
|
|
|
|
if update.Content != "" {
|
|
note.Content = update.Content
|
|
}
|
|
if update.Title != "" {
|
|
note.Title = update.Title
|
|
}
|
|
|
|
if err := isNoteVaid(note); err != nil {
|
|
return models.Note{}, err
|
|
}
|
|
|
|
note.LastUpdate = time.Now()
|
|
return r.store.SaveNote(ctx, note)
|
|
}
|
|
|
|
// DeleteNote deletes a note by its ID.
|
|
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
|
|
} |