-
Notifications
You must be signed in to change notification settings - Fork 321
/
in_memory_repository.go
82 lines (62 loc) · 1.76 KB
/
in_memory_repository.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
74
75
76
77
78
79
80
81
82
package api
import (
"context"
"sync"
log "github.com/sirupsen/logrus"
)
// InMemoryRepository represents a in memory repository
type InMemoryRepository struct {
sync.RWMutex
definitions map[string]*Definition
}
// NewInMemoryRepository creates a in memory repository
func NewInMemoryRepository() *InMemoryRepository {
return &InMemoryRepository{definitions: make(map[string]*Definition)}
}
// Close terminates the session. It's a runtime error to use a session
// after it has been closed.
func (r *InMemoryRepository) Close() error {
return nil
}
// Watch watches for changes on the database
func (r *InMemoryRepository) Watch(ctx context.Context, cfgChan chan<- ConfigurationChanged) {
}
// FindAll fetches all the api definitions available
func (r *InMemoryRepository) FindAll() ([]*Definition, error) {
r.RLock()
defer r.RUnlock()
var definitions []*Definition
for _, definition := range r.definitions {
definitions = append(definitions, definition)
}
return definitions, nil
}
func (r *InMemoryRepository) findByName(name string) (*Definition, error) {
definition, ok := r.definitions[name]
if false == ok {
return nil, ErrAPIDefinitionNotFound
}
return definition, nil
}
// Add adds an api definition to the repository
func (r *InMemoryRepository) add(definition *Definition) error {
r.Lock()
defer r.Unlock()
isValid, err := definition.Validate()
if false == isValid && err != nil {
log.WithError(err).Error("Validation errors")
return err
}
r.definitions[definition.Name] = definition
return nil
}
// Remove removes an api definition from the repository
func (r *InMemoryRepository) remove(name string) error {
r.Lock()
defer r.Unlock()
if _, err := r.findByName(name); err != nil {
return err
}
delete(r.definitions, name)
return nil
}