81 lines
2.3 KiB
Go
81 lines
2.3 KiB
Go
package store
|
|
|
|
import (
|
|
"fmt"
|
|
"path/filepath"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"printer.backend/internal/model"
|
|
"printer.backend/internal/paths"
|
|
)
|
|
|
|
// ConfigurationStore persists configurations as JSON files.
|
|
type ConfigurationStore struct {
|
|
dir string
|
|
}
|
|
|
|
// NewConfigurationStore creates a store under dir (default data/configurations).
|
|
func NewConfigurationStore(dir string) *ConfigurationStore {
|
|
if dir == "" {
|
|
dir = paths.ConfigurationsDir
|
|
}
|
|
return &ConfigurationStore{dir: dir}
|
|
}
|
|
|
|
// List returns all configurations sorted by creation time (newest first).
|
|
func (s *ConfigurationStore) List() ([]model.Configuration, error) {
|
|
return listFromDir(s.dir,
|
|
func(name string) bool { return filepath.Ext(name) == ".json" },
|
|
"configurations dir",
|
|
func(c model.Configuration) time.Time { return c.CreatedAt },
|
|
)
|
|
}
|
|
|
|
// Get returns a configuration by ID.
|
|
func (s *ConfigurationStore) Get(id string) (model.Configuration, error) {
|
|
list, err := s.List()
|
|
if err != nil {
|
|
return model.Configuration{}, err
|
|
}
|
|
return findByID(list, id, func(c model.Configuration) string { return c.ID })
|
|
}
|
|
|
|
// Save writes a new configuration and assigns an ID when empty.
|
|
func (s *ConfigurationStore) Save(c model.Configuration) (model.Configuration, error) {
|
|
if err := ensureDir(s.dir); err != nil {
|
|
return model.Configuration{}, err
|
|
}
|
|
if c.ID == "" {
|
|
c.ID = uuid.NewString()
|
|
}
|
|
c.CreatedAt = stampNew(&c.CreatedAt)
|
|
|
|
path := filepath.Join(s.dir, c.ID+".json")
|
|
if err := writeJSON(path, c); err != nil {
|
|
return model.Configuration{}, fmt.Errorf("write configuration: %w", err)
|
|
}
|
|
return c, nil
|
|
}
|
|
|
|
// Update replaces an existing configuration by ID (preserves created_at).
|
|
func (s *ConfigurationStore) Update(id string, c model.Configuration) (model.Configuration, error) {
|
|
path := filepath.Join(s.dir, id+".json")
|
|
existing, err := readJSON[model.Configuration](path)
|
|
if err != nil {
|
|
return model.Configuration{}, fmt.Errorf("configuration not found: %s", id)
|
|
}
|
|
c.ID = existing.ID
|
|
c.CreatedAt = existing.CreatedAt
|
|
if err := writeJSON(path, c); err != nil {
|
|
return model.Configuration{}, fmt.Errorf("write configuration: %w", err)
|
|
}
|
|
return c, nil
|
|
}
|
|
|
|
// Delete removes a configuration by ID.
|
|
func (s *ConfigurationStore) Delete(id string) error {
|
|
path := filepath.Join(s.dir, id+".json")
|
|
return removeFile(path, fmt.Sprintf("configuration not found: %s", id))
|
|
}
|