Added Configuration from Item and Plate
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
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
|
||||
}
|
||||
|
||||
// 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))
|
||||
}
|
||||
Reference in New Issue
Block a user