probo/store/file/collection.go

54 lines
1.1 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"
)
2023-11-13 21:01:12 +01:00
func NewCollectionFileStore() (*FileStore[*models.Collection, *store.Store[*models.Collection]], error) {
return NewFileStore[*models.Collection](
store.NewStore[*models.Collection](),
filepath.Join(BaseDir, CollectionsDir),
"collection",
".json",
func(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(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
},
)
}