Files
RenewCMS/internal/infrastructure/update/jsonResultStore.go
T

53 lines
1.0 KiB
Go

package update
import (
domain "RenewCMS/internal/domain/update"
"encoding/json"
"os"
"sync"
)
type JSONResultStore struct {
path string
mu sync.Mutex
}
var _ domain.ResultStore = &JSONResultStore{}
func NewJSONResultStore(path string) *JSONResultStore {
return &JSONResultStore{path: path}
}
func (s *JSONResultStore) Read() (domain.Result, bool) {
s.mu.Lock()
defer s.mu.Unlock()
content, err := os.ReadFile(s.path)
if err != nil {
return domain.Result{}, false
}
return decodeResult(content)
}
func (s *JSONResultStore) Write(result domain.Result) error {
s.mu.Lock()
defer s.mu.Unlock()
return writeJSONAtomically(s.path, result, readableFilePermissions)
}
func (s *JSONResultStore) Delete() error {
s.mu.Lock()
defer s.mu.Unlock()
return removeIfPresent(s.path)
}
func decodeResult(content []byte) (domain.Result, bool) {
var result domain.Result
if err := json.Unmarshal(content, &result); err != nil || !result.IsKnown() {
return domain.Result{}, false
}
return result, true
}