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) }