Files
superherohub/pkg/deesee/storage/storage.go

47 lines
1015 B
Go

package storage
import (
"encoding/json"
"errors"
"fmt"
"github.com/eslider/superherohub/pkg/deesee"
"os"
"strings"
)
type DeeSee []*deesee.Superhero
// New DeeSee storage.
func New(path string) (d *DeeSee, err error) {
d = &DeeSee{}
err = d.Load(path)
return
}
// Load superheroes from json file
func (s *DeeSee) Load(path string) (err error) {
// Read and unmarshal s from json f path
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)
}
// Store superhero
func (s *DeeSee) Store(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, strings.TrimSpace(hero.Name)) != nil {
return errors.New(fmt.Sprintf("Hero already exists: %s", hero.Name))
}
*s = append(*s, hero)
return
}