OSDN Git Service

change the ts (#284)
[bytom/vapor.git] / federation / database / asset_store.go
1 package database
2
3 import (
4         "fmt"
5
6         "github.com/golang/groupcache/lru"
7         "github.com/jinzhu/gorm"
8
9         "github.com/vapor/errors"
10         "github.com/vapor/federation/database/orm"
11 )
12
13 const (
14         maxAssetCached = 1024
15
16         ormIDPrefix   = "ormID"
17         assetIDPrefix = "assetID"
18 )
19
20 func fmtOrmIDKey(ormID uint64) string {
21         return fmt.Sprintf("%s:%d", ormIDPrefix, ormID)
22 }
23
24 func fmtAssetIDKey(assetID string) string {
25         return fmt.Sprintf("%s:%s", assetIDPrefix, assetID)
26 }
27
28 type AssetStore struct {
29         cache *lru.Cache
30         db    *gorm.DB
31 }
32
33 func NewAssetStore(db *gorm.DB) *AssetStore {
34         return &AssetStore{
35                 cache: lru.New(maxAssetCached),
36                 db:    db,
37         }
38 }
39
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
43         }
44
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")
48         }
49
50         a.cache.Add(fmtOrmIDKey(asset.ID), asset)
51         a.cache.Add(fmtAssetIDKey(asset.AssetID), asset)
52         return asset, nil
53 }
54
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
58         }
59
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")
63         }
64
65         a.cache.Add(fmtOrmIDKey(asset.ID), asset)
66         a.cache.Add(fmtAssetIDKey(asset.AssetID), asset)
67         return asset, nil
68 }