| 1 |
package storage |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"sort" |
| 6 |
|
| 7 |
"github.com/manyminds/api2go/examples/model" |
| 8 |
) |
| 9 |
|
| 10 |
// sorting |
| 11 |
type byID []model.Chocolate |
| 12 |
|
| 13 |
func (c byID) Len() int { |
| 14 |
return len(c) |
| 15 |
} |
| 16 |
|
| 17 |
func (c byID) Swap(i, j int) { |
| 18 |
c[i], c[j] = c[j], c[i] |
| 19 |
} |
| 20 |
|
| 21 |
func (c byID) Less(i, j int) bool { |
| 22 |
return c[i].GetID() < c[j].GetID() |
| 23 |
} |
| 24 |
|
| 25 |
// NewChocolateStorage initializes the storage |
| 26 |
func NewChocolateStorage() *ChocolateStorage { |
| 27 |
return &ChocolateStorage{make(map[string]*model.Chocolate), 1} |
| 28 |
} |
| 29 |
|
| 30 |
// ChocolateStorage stores all of the tasty chocolate, needs to be injected into |
| 31 |
// User and Chocolate Resource. In the real world, you would use a database for that. |
| 32 |
type ChocolateStorage struct { |
| 33 |
chocolates map[string]*model.Chocolate |
| 34 |
idCount int |
| 35 |
} |
| 36 |
|
| 37 |
// GetAll of the chocolate |
| 38 |
func (s ChocolateStorage) GetAll() []model.Chocolate { |
| 39 |
result := []model.Chocolate{} |
| 40 |
for key := range s.chocolates { |
| 41 |
result = append(result, *s.chocolates[key]) |
| 42 |
} |
| 43 |
|
| 44 |
sort.Sort(byID(result)) |
| 45 |
return result |
| 46 |
} |
| 47 |
|
| 48 |
// GetOne tasty chocolate |
| 49 |
func (s ChocolateStorage) GetOne(id string) (model.Chocolate, error) { |
| 50 |
choc, ok := s.chocolates[id] |
| 51 |
if ok { |
| 52 |
return *choc, nil |
| 53 |
} |
| 54 |
|
| 55 |
return model.Chocolate{}, fmt.Errorf("Chocolate for id %s not found", id) |
| 56 |
} |
| 57 |
|
| 58 |
// Insert a fresh one |
| 59 |
func (s *ChocolateStorage) Insert(c model.Chocolate) string { |
| 60 |
id := fmt.Sprintf("%d", s.idCount) |
| 61 |
c.ID = id |
| 62 |
s.chocolates[id] = &c |
| 63 |
s.idCount++ |
| 64 |
return id |
| 65 |
} |
| 66 |
|
| 67 |
// Delete one :( |
| 68 |
func (s *ChocolateStorage) Delete(id string) error { |
| 69 |
_, exists := s.chocolates[id] |
| 70 |
if !exists { |
| 71 |
return fmt.Errorf("Chocolate with id %s does not exist", id) |
| 72 |
} |
| 73 |
delete(s.chocolates, id) |
| 74 |
|
| 75 |
return nil |
| 76 |
} |
| 77 |
|
| 78 |
// Update updates an existing chocolate |
| 79 |
func (s *ChocolateStorage) Update(c model.Chocolate) error { |
| 80 |
_, exists := s.chocolates[c.ID] |
| 81 |
if !exists { |
| 82 |
return fmt.Errorf("Chocolate with id %s does not exist", c.ID) |
| 83 |
} |
| 84 |
s.chocolates[c.ID] = &c |
| 85 |
|
| 86 |
return nil |
| 87 |
} |