Refactor router and storage
* Split and extract data-logic from application level * Move storage to DeeSee package * Move router into internal package * Fix Makefile * Fix documentation * Fix tests
This commit is contained in:
56
pkg/deesee/storage/storage.go
Normal file
56
pkg/deesee/storage/storage.go
Normal file
@@ -0,0 +1,56 @@
|
||||
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
|
||||
}
|
||||
|
||||
// FindByName from superheros list
|
||||
func (s *DeeSee) FindByName(name string) *deesee.Superhero {
|
||||
for _, hero := range *s {
|
||||
if strings.EqualFold(name, hero.Name) {
|
||||
return hero
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user