-
Notifications
You must be signed in to change notification settings - Fork 13
/
storage.go
73 lines (64 loc) · 1.73 KB
/
storage.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package monstrg
import (
"context"
"encoding/json"
"fmt"
"github.com/Haraj-backend/hex-monscape/internal/core/entity"
"gopkg.in/validator.v2"
)
type Storage struct {
partnerMap map[string]entity.Monster
enemyMap map[string]entity.Monster
}
func (s *Storage) GetAvailablePartners(ctx context.Context) ([]entity.Monster, error) {
var partners []entity.Monster
for _, partner := range s.partnerMap {
partners = append(partners, partner)
}
return partners, nil
}
func (s *Storage) GetPartner(ctx context.Context, partnerID string) (*entity.Monster, error) {
partner, ok := s.partnerMap[partnerID]
if !ok {
return nil, nil
}
return &partner, nil
}
func (s *Storage) GetPossibleEnemies(ctx context.Context) ([]entity.Monster, error) {
var enemies []entity.Monster
for _, enemy := range s.enemyMap {
enemies = append(enemies, enemy)
}
return enemies, nil
}
type Config struct {
MonsterData []byte `validate:"nonzero"`
}
func (c Config) Validate() error {
return validator.Validate(c)
}
func New(cfg Config) (*Storage, error) {
// validate config
err := cfg.Validate()
if err != nil {
return nil, fmt.Errorf("invalid config: %w", err)
}
// parse monster data
var rows []monsterRow
err = json.Unmarshal(cfg.MonsterData, &rows)
if err != nil {
return nil, fmt.Errorf("unable to parse monster data due: %w", err)
}
partnerMap := map[string]entity.Monster{}
enemyMap := map[string]entity.Monster{}
for _, monsterRow := range rows {
// we want every monster to be fightable
monster := monsterRow.toMonster()
enemyMap[monster.ID] = monster
// add to partner map if it is partnerable
if monsterRow.IsPartnerable {
partnerMap[monster.ID] = monster
}
}
return &Storage{partnerMap: partnerMap, enemyMap: enemyMap}, nil
}