-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstorage_mem.go
69 lines (53 loc) · 1.48 KB
/
storage_mem.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
package main
import (
"fmt"
)
type memStorage struct {
services map[string][]Entity
}
func CreateMemStorage(serviceNames []string) *memStorage {
serviceMap := make(map[string][]Entity)
for _, serviceName := range serviceNames {
serviceMap[serviceName] = []Entity{}
}
return &memStorage{services: serviceMap}
}
func (storage *memStorage) Add(serviceName string, payload interface{}) (Entity, error) {
e, err := createEntity(payload)
if err != nil {
return e, err
}
storage.AddEntity(serviceName, e)
return e, nil
}
func (storage *memStorage) AddEntity(serviceName string, e Entity) {
storage.services[serviceName] = append(storage.services[serviceName], e)
}
func (storage *memStorage) List(serviceName string) ([]Entity, error) {
return storage.services[serviceName], nil
}
func (storage *memStorage) Get(serviceName, id string) (Entity, error) {
for _, entity := range storage.services[serviceName] {
if entity.Id == id {
return entity, nil
}
}
return Entity{}, fmt.Errorf("could not find entity with id %q", id)
}
func (storage *memStorage) Delete(serviceName, id string) error {
// find ID
idx := 0
found := false
for k, entity := range storage.services[serviceName] {
if entity.Id == id {
idx = k
found = true
}
}
if !found {
return fmt.Errorf("could not find id %q in entity list", id)
}
// delete ID from list
storage.services[serviceName] = append(storage.services[serviceName][:idx], storage.services[serviceName][idx+1:]...)
return nil
}