bbgo_origin/pkg/bbgo/persistence.go

67 lines
1.5 KiB
Go
Raw Normal View History

package bbgo
import (
"fmt"
"github.com/c9s/bbgo/pkg/service"
)
2020-12-07 03:43:17 +00:00
type PersistenceSelector struct {
// StoreID is the store you want to use.
StoreID string `json:"store" yaml:"store"`
// Type is the persistence type
Type string `json:"type" yaml:"type"`
}
// Persistence is used for strategy to inject the persistence.
type Persistence struct {
PersistenceSelector *PersistenceSelector `json:"persistence,omitempty" yaml:"persistence,omitempty"`
Facade *service.PersistenceServiceFacade `json:"-" yaml:"-"`
2020-12-07 03:43:17 +00:00
}
2021-03-18 09:20:07 +00:00
func (p *Persistence) backendService(t string) (service.PersistenceService, error) {
2020-12-07 03:43:17 +00:00
switch t {
case "json":
2021-03-18 09:20:07 +00:00
return p.Facade.Json, nil
2020-12-07 03:43:17 +00:00
case "redis":
2021-03-18 09:20:07 +00:00
return p.Facade.Redis, nil
2020-12-07 03:43:17 +00:00
2020-12-07 04:03:56 +00:00
case "memory":
2021-03-18 09:20:07 +00:00
return p.Facade.Memory, nil
2020-12-07 04:03:56 +00:00
2020-12-07 03:43:17 +00:00
}
2021-03-18 09:20:07 +00:00
return nil, fmt.Errorf("unsupported persistent type %s", t)
2020-12-07 03:43:17 +00:00
}
func (p *Persistence) Load(val interface{}, subIDs ...string) error {
2021-03-18 09:20:07 +00:00
ps, err := p.backendService(p.PersistenceSelector.Type)
2020-12-07 03:43:17 +00:00
if err != nil {
return err
}
if p.PersistenceSelector.StoreID == "" {
2021-03-18 09:20:07 +00:00
p.PersistenceSelector.StoreID = "default"
2020-12-07 03:43:17 +00:00
}
2021-03-18 09:20:07 +00:00
store := ps.NewStore(p.PersistenceSelector.StoreID, subIDs...)
2020-12-07 03:43:17 +00:00
return store.Load(val)
}
func (p *Persistence) Save(val interface{}, subIDs ...string) error {
2021-03-18 09:20:07 +00:00
ps, err := p.backendService(p.PersistenceSelector.Type)
2020-12-07 03:43:17 +00:00
if err != nil {
return err
}
if p.PersistenceSelector.StoreID == "" {
2021-03-18 09:20:07 +00:00
p.PersistenceSelector.StoreID = "default"
2020-12-07 03:43:17 +00:00
}
2021-03-18 09:20:07 +00:00
store := ps.NewStore(p.PersistenceSelector.StoreID, subIDs...)
2020-12-07 03:43:17 +00:00
return store.Save(val)
}