bbgo_origin/pkg/bbgo/cache.go

71 lines
1.4 KiB
Go
Raw Normal View History

2020-10-20 04:11:44 +00:00
package bbgo
import (
2021-02-19 02:42:24 +00:00
"context"
2020-10-20 04:11:44 +00:00
"encoding/json"
2021-02-19 02:42:24 +00:00
"fmt"
2020-10-20 04:11:44 +00:00
"io/ioutil"
"os"
"path"
"reflect"
"github.com/pkg/errors"
2021-02-19 02:42:24 +00:00
"github.com/c9s/bbgo/pkg/types"
2020-10-20 04:11:44 +00:00
)
2020-10-20 04:22:18 +00:00
type DataFetcher func() (interface{}, error)
// WithCache let you use the cache with the given cache key, variable reference and your data fetcher,
// The key must be an unique ID.
// obj is the pointer of your local variable
// fetcher is the closure that will fetch your remote data or some slow operation.
func WithCache(key string, obj interface{}, fetcher DataFetcher) error {
2020-10-20 04:11:44 +00:00
cacheDir := CacheDir()
2020-10-20 04:24:30 +00:00
cacheFile := path.Join(cacheDir, key+".json")
2020-10-20 04:11:44 +00:00
if _, err := os.Stat(cacheFile); os.IsNotExist(err) {
2020-10-20 04:22:18 +00:00
data, err := fetcher()
2020-10-20 04:11:44 +00:00
if err != nil {
return err
}
out, err := json.Marshal(data)
if err != nil {
return err
}
if err := ioutil.WriteFile(cacheFile, out, 0666); err != nil {
return err
}
rv := reflect.ValueOf(obj).Elem()
if !rv.CanSet() {
return errors.New("can not set cache object value")
}
rv.Set(reflect.ValueOf(data))
} else {
data, err := ioutil.ReadFile(cacheFile)
if err != nil {
return err
}
if err := json.Unmarshal(data, obj); err != nil {
return err
}
}
return nil
}
2021-02-19 02:42:24 +00:00
func LoadExchangeMarketsWithCache(ctx context.Context, ex types.Exchange) (markets types.MarketMap, err error) {
err = WithCache(fmt.Sprintf("%s-markets", ex.Name()), &markets, func() (interface{}, error) {
return ex.QueryMarkets(ctx)
})
return markets, err
}