github.com/NpoolPlatform/chain-middleware@v0.0.0-20240228100535-eb1bcf896eb9/pkg/mw/coin/currency/feed/create.go (about) 1 package currencyfeed 2 3 import ( 4 "context" 5 "fmt" 6 7 currencyfeedcrud "github.com/NpoolPlatform/chain-middleware/pkg/crud/coin/currency/feed" 8 redis2 "github.com/NpoolPlatform/go-service-framework/pkg/redis" 9 basetypes "github.com/NpoolPlatform/message/npool/basetypes/v1" 10 npool "github.com/NpoolPlatform/message/npool/chain/mw/v1/coin/currency/feed" 11 12 "github.com/NpoolPlatform/chain-middleware/pkg/db" 13 "github.com/NpoolPlatform/chain-middleware/pkg/db/ent" 14 "github.com/NpoolPlatform/libent-cruder/pkg/cruder" 15 16 "github.com/google/uuid" 17 ) 18 19 func (h *Handler) CreateFeed(ctx context.Context) (*npool.Feed, error) { 20 if h.FeedCoinName == nil { 21 return nil, fmt.Errorf("invalid feedcoinname") 22 } 23 24 lockKey := fmt.Sprintf( 25 "%v:%v:%v", 26 basetypes.Prefix_PrefixCreateCoinCurrencyFeed, 27 *h.CoinTypeID, 28 *h.FeedType, 29 ) 30 if err := redis2.TryLock(lockKey, 0); err != nil { 31 return nil, err 32 } 33 defer func() { 34 _ = redis2.Unlock(lockKey) 35 }() 36 37 h.Conds = ¤cyfeedcrud.Conds{ 38 CoinTypeID: &cruder.Cond{Op: cruder.EQ, Val: *h.CoinTypeID}, 39 FeedType: &cruder.Cond{Op: cruder.EQ, Val: *h.FeedType}, 40 } 41 exist, err := h.ExistFeedConds(ctx) 42 if err != nil { 43 return nil, err 44 } 45 if exist { 46 return nil, fmt.Errorf("coinfeed exist") 47 } 48 49 id := uuid.New() 50 if h.EntID == nil { 51 h.EntID = &id 52 } 53 54 err = db.WithClient(ctx, func(_ctx context.Context, cli *ent.Client) error { 55 if _, err := currencyfeedcrud.CreateSet( 56 cli.CurrencyFeed.Create(), 57 ¤cyfeedcrud.Req{ 58 EntID: h.EntID, 59 CoinTypeID: h.CoinTypeID, 60 FeedType: h.FeedType, 61 FeedCoinName: h.FeedCoinName, 62 Disabled: h.Disabled, 63 }, 64 ).Save(_ctx); err != nil { 65 return err 66 } 67 return nil 68 }) 69 if err != nil { 70 return nil, err 71 } 72 73 return h.GetFeed(ctx) 74 }