102 lines
2.1 KiB
Go
Raw Normal View History

2023-07-07 16:05:52 +00:00
package ocean
import (
"os"
"path/filepath"
"strings"
)
// DirectoryStorage creates a directory and stores every record in a separate file.
type DirectoryStorage[T any] struct {
collection *collection[T]
directory string
}
// Init loads all existing records from the directory.
func (ds *DirectoryStorage[T]) Init(c *collection[T]) error {
ds.collection = c
ds.directory = filepath.Join(c.root, c.name)
os.Mkdir(ds.directory, 0700)
2023-07-08 15:26:36 +00:00
return ds.read()
2023-07-07 16:05:52 +00:00
}
// Set saves the value in a file.
func (ds *DirectoryStorage[T]) Set(key string, value *T) error {
2023-07-08 15:26:36 +00:00
return ds.writeFile(key, value)
2023-07-07 16:05:52 +00:00
}
// Delete deletes the file for the given key.
func (ds *DirectoryStorage[T]) Delete(key string) error {
return os.Remove(ds.keyFile(key))
}
2023-07-08 15:26:36 +00:00
// read loads the collection data from the disk.
func (ds *DirectoryStorage[T]) read() error {
2023-07-07 16:05:52 +00:00
dir, err := os.Open(ds.directory)
if err != nil {
return err
}
defer dir.Close()
files, err := dir.Readdirnames(0)
for _, fileName := range files {
2023-07-08 15:26:36 +00:00
fileError := ds.readFile(fileName)
2023-07-07 16:05:52 +00:00
if fileError != nil {
return fileError
}
}
return err
}
2023-07-08 15:26:36 +00:00
// readFile loads a single file from the disk.
func (ds *DirectoryStorage[T]) readFile(fileName string) error {
fileName = filepath.Join(ds.directory, fileName)
file, err := os.Open(fileName)
2023-07-07 16:05:52 +00:00
if err != nil {
return err
}
2023-07-08 15:26:36 +00:00
defer file.Close()
2023-07-07 16:05:52 +00:00
value := new(T)
decoder := NewDecoder(file)
err = decoder.Decode(value)
if err != nil {
return err
}
key := strings.TrimSuffix(fileName, ".json")
ds.collection.data.Store(key, value)
2023-07-08 15:26:36 +00:00
return nil
2023-07-07 16:05:52 +00:00
}
2023-07-08 15:26:36 +00:00
// writeFile writes the value for the key to disk as a JSON file.
func (ds *DirectoryStorage[T]) writeFile(key string, value *T) error {
2023-07-07 16:05:52 +00:00
fileName := ds.keyFile(key)
file, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600)
if err != nil {
return err
}
encoder := NewEncoder(file)
err = encoder.Encode(value)
if err != nil {
file.Close()
return err
}
return file.Close()
}
2023-07-08 15:26:36 +00:00
// keyFile returns the file path for the given key.
func (ds *DirectoryStorage[T]) keyFile(key string) string {
return filepath.Join(ds.directory, key+".json")
}