-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
factory.go
65 lines (53 loc) · 1.91 KB
/
factory.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
package hypercache
import (
"github.com/hyp3rd/hypercache/backend"
"github.com/hyp3rd/hypercache/errors"
)
// IBackendConstructor is an interface for backend constructors
type IBackendConstructor interface {
Create(config interface{}) (interface{}, error)
}
// InMemoryBackendConstructor is a backend constructor for InMemory
type InMemoryBackendConstructor struct{}
// Create creates a new InMemory backend
func (ibc InMemoryBackendConstructor) Create(config interface{}) (interface{}, error) {
inMemoryConfig, ok := config.(*Config[backend.InMemory])
if !ok {
return nil, errors.ErrInvalidBackendType
}
return backend.NewInMemory(inMemoryConfig.InMemoryOptions...)
}
// RedisBackendConstructor is a backend constructor for Redis
type RedisBackendConstructor struct{}
// Create creates a new Redis backend
func (rbc RedisBackendConstructor) Create(config interface{}) (interface{}, error) {
redisConfig, ok := config.(*Config[backend.Redis])
if !ok {
return nil, errors.ErrInvalidBackendType
}
return backend.NewRedis(redisConfig.RedisOptions...)
}
// BackendManager is a factory for creating HyperCache backend instances
type BackendManager struct {
backendRegistry map[string]IBackendConstructor
}
// NewBackendManager creates a new BackendManager
func NewBackendManager() *BackendManager {
return &BackendManager{
backendRegistry: make(map[string]IBackendConstructor),
}
}
// RegisterBackend registers a new backend constructor
func (hcm *BackendManager) RegisterBackend(name string, constructor IBackendConstructor) {
hcm.backendRegistry[name] = constructor
}
var defaultManager *BackendManager
// GetDefaultManager returns the default BackendManager
func GetDefaultManager() *BackendManager {
return defaultManager
}
func init() {
defaultManager = NewBackendManager()
defaultManager.RegisterBackend("in-memory", InMemoryBackendConstructor{})
defaultManager.RegisterBackend("redis", RedisBackendConstructor{})
}