Refactor and rename storage to Json

This commit is contained in:
2023-02-08 18:33:44 +00:00
parent 6aebdc8b5e
commit 38a200c648
5 changed files with 90 additions and 66 deletions

View File

@@ -0,0 +1,65 @@
package storage
import (
"encoding/json"
"errors"
"fmt"
"github.com/eslider/superherohub/pkg/deesee"
"os"
"strings"
)
// Json simple JSON memory storage.
type Json struct {
path string // Path to json file
list []*deesee.Superhero // List of loaded superheroes
}
// NewJson Json storage.
func NewJson(path string) (d *Json, err error) {
d = &Json{
path: path,
}
err = d.Load(path)
return
}
// Load superheroes from JSON file.
func (s *Json) Load(path string) error {
f, err := os.OpenFile(path, os.O_RDONLY, 0644)
if err != nil {
return fmt.Errorf("unable to read f: %w", err)
}
return json.NewDecoder(f).Decode(&s.list)
}
// List superheros
func (s *Json) List() []*deesee.Superhero {
return s.list
}
// Put superhero.
func (s *Json) Put(hero *deesee.Superhero) (err error) {
// Check if superhero superpower is acceptable
if !hero.IsAcceptable() {
return errors.New(fmt.Sprintf("Hero power is not acceptable: %s", hero.Name))
}
// Prevent to store duplicate superheroes
if deesee.FindByName(s.list, strings.TrimSpace(hero.Name)) != nil {
return errors.New(fmt.Sprintf("Hero already exists: %s", hero.Name))
}
s.list = append(s.list, hero)
return
}
// Persist superheroes to JSON file.
func (s *Json) Persist() error {
f, err := os.OpenFile(s.path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
return fmt.Errorf("unable to write file: %w", err)
}
return json.NewEncoder(f).Encode(s.list)
}