probo/store/file/collection.go

55 lines
1.2 KiB
Go
Raw Normal View History

package file
import (
"encoding/json"
"os"
"path/filepath"
"git.andreafazzi.eu/andrea/probo/models"
2023-11-13 21:01:12 +01:00
"git.andreafazzi.eu/andrea/probo/store"
)
type CollectionFileStore = FileStore[*models.Collection, *store.Store[*models.Collection]]
var DefaultCollectionDir = filepath.Join(BaseDir, CollectionsDir)
func NewCollectionFileStore(config *FileStoreConfig[*models.Collection, *store.CollectionStore]) (*CollectionFileStore, error) {
return NewFileStore[*models.Collection](config, store.NewStore[*models.Collection]())
}
func DefaultUnmarshalCollectionFunc(s *store.Store[*models.Collection], filepath string, content []byte) (*models.Collection, error) {
collection := new(models.Collection)
err := json.Unmarshal(content, &collection)
if err != nil {
return nil, err
}
c, err := s.Create(collection)
if err != nil {
return nil, err
}
return c, nil
}
func DefaultMarshalCollectionFunc(s *store.Store[*models.Collection], filePath string, collection *models.Collection) error {
jsonData, err := json.Marshal(collection)
if err != nil {
return err
}
file, err := os.Create(filePath)
if err != nil {
return err
}
defer file.Close()
_, err = file.Write(jsonData)
if err != nil {
return err
}
return nil
}