github.com/NpoolPlatform/chain-middleware@v0.0.0-20240228100535-eb1bcf896eb9/pkg/mw/coin/fiat/create.go (about) 1 package coinfiat 2 3 import ( 4 "context" 5 "fmt" 6 7 coinfiatcrud "github.com/NpoolPlatform/chain-middleware/pkg/crud/coin/fiat" 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/fiat" 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 17 func (h *Handler) CreateCoinFiat(ctx context.Context) (*npool.CoinFiat, error) { 18 lockKey := fmt.Sprintf( 19 "%v:%v:%v", 20 basetypes.Prefix_PrefixCreateCoinFiat, 21 *h.CoinTypeID, 22 *h.FiatID, 23 ) 24 if err := redis2.TryLock(lockKey, 0); err != nil { 25 return nil, err 26 } 27 defer func() { 28 _ = redis2.Unlock(lockKey) 29 }() 30 31 h.Conds = &coinfiatcrud.Conds{ 32 CoinTypeID: &cruder.Cond{Op: cruder.EQ, Val: *h.CoinTypeID}, 33 FiatID: &cruder.Cond{Op: cruder.EQ, Val: *h.FiatID}, 34 } 35 exist, err := h.ExistCoinConds(ctx) 36 if err != nil { 37 return nil, err 38 } 39 if exist { 40 return nil, fmt.Errorf("coinfiat exist") 41 } 42 43 err = db.WithClient(ctx, func(_ctx context.Context, cli *ent.Client) error { 44 info, err := coinfiatcrud.CreateSet( 45 cli.CoinFiat.Create(), 46 &coinfiatcrud.Req{ 47 CoinTypeID: h.CoinTypeID, 48 FiatID: h.FiatID, 49 FeedType: h.FeedType, 50 }, 51 ).Save(_ctx) 52 if err != nil { 53 return err 54 } 55 56 h.ID = &info.ID 57 58 return nil 59 }) 60 if err != nil { 61 return nil, err 62 } 63 64 return h.GetCoinFiat(ctx) 65 }