81 lines
2.0 KiB
Go
81 lines
2.0 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"git.hrafn.xyz/aether/gotes/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 := note.Validate(); 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{}, &ErrEmptyUpdate{}
|
|
}
|
|
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{}, &ErrNoOP{}
|
|
}
|
|
|
|
if update.Content != "" {
|
|
note.Content = update.Content
|
|
}
|
|
if update.Title != "" {
|
|
note.Title = update.Title
|
|
}
|
|
|
|
if err := note.Validate(); 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)
|
|
}
|