6 "github.com/golang/groupcache/lru"
7 "github.com/jinzhu/gorm"
9 "github.com/vapor/errors"
10 "github.com/vapor/federation/database/orm"
17 assetIDPrefix = "assetID"
20 func fmtOrmIDKey(ormID uint64) string {
21 return fmt.Sprintf("%s:%d", ormIDPrefix, ormID)
24 func fmtAssetIDKey(assetID string) string {
25 return fmt.Sprintf("%s:%s", assetIDPrefix, assetID)
28 type AssetStore struct {
33 func NewAssetStore(db *gorm.DB) *AssetStore {
35 cache: lru.New(maxAssetCached),
40 func (a *AssetStore) GetByOrmID(ormID uint64) (*orm.Asset, error) {
41 if v, ok := a.cache.Get(fmtOrmIDKey(ormID)); ok {
42 return v.(*orm.Asset), nil
45 asset := &orm.Asset{ID: ormID}
46 if err := a.db.Where(asset).First(asset).Error; err != nil {
47 return nil, errors.Wrap(err, "asset not found by orm id")
50 a.cache.Add(fmtOrmIDKey(asset.ID), asset)
51 a.cache.Add(fmtAssetIDKey(asset.AssetID), asset)
55 func (a *AssetStore) GetByAssetID(assetID string) (*orm.Asset, error) {
56 if v, ok := a.cache.Get(fmtAssetIDKey(assetID)); ok {
57 return v.(*orm.Asset), nil
60 asset := &orm.Asset{AssetID: assetID}
61 if err := a.db.Where(asset).First(asset).Error; err != nil {
62 return nil, errors.Wrap(err, "asset not found in memory and mysql")
65 a.cache.Add(fmtOrmIDKey(asset.ID), asset)
66 a.cache.Add(fmtAssetIDKey(asset.AssetID), asset)
70 func (a *AssetStore) Add(asset *orm.Asset) error {
71 if err := a.db.Create(asset).Error; err != nil {
75 a.cache.Add(fmtOrmIDKey(asset.ID), asset)
76 a.cache.Add(fmtAssetIDKey(asset.AssetID), asset)