github.com/NpoolPlatform/chain-middleware@v0.0.0-20240228100535-eb1bcf896eb9/pkg/client/coin/currency/client.go (about) 1 package currency 2 3 import ( 4 "context" 5 "time" 6 7 grpc2 "github.com/NpoolPlatform/go-service-framework/pkg/grpc" 8 9 "github.com/NpoolPlatform/libent-cruder/pkg/cruder" 10 npool "github.com/NpoolPlatform/message/npool/chain/mw/v1/coin/currency" 11 12 servicename "github.com/NpoolPlatform/chain-middleware/pkg/servicename" 13 ) 14 15 var timeout = 10 * time.Second 16 17 type handler func(context.Context, npool.MiddlewareClient) (cruder.Any, error) 18 19 func withCRUD(ctx context.Context, handler handler) (cruder.Any, error) { 20 _ctx, cancel := context.WithTimeout(ctx, timeout) 21 defer cancel() 22 23 conn, err := grpc2.GetGRPCConn(servicename.ServiceDomain, grpc2.GRPCTAG) 24 if err != nil { 25 return nil, err 26 } 27 28 defer conn.Close() 29 30 cli := npool.NewMiddlewareClient(conn) 31 32 return handler(_ctx, cli) 33 } 34 35 func GetCurrency(ctx context.Context, id string) (*npool.Currency, error) { 36 info, err := withCRUD(ctx, func(_ctx context.Context, cli npool.MiddlewareClient) (cruder.Any, error) { 37 resp, err := cli.GetCurrency(ctx, &npool.GetCurrencyRequest{ 38 EntID: id, 39 }) 40 if err != nil { 41 return nil, err 42 } 43 return resp.Info, nil 44 }) 45 if err != nil { 46 return nil, err 47 } 48 return info.(*npool.Currency), nil 49 } 50 51 func GetCurrencies(ctx context.Context, conds *npool.Conds, offset, limit int32) ([]*npool.Currency, uint32, error) { 52 total := uint32(0) 53 54 infos, err := withCRUD(ctx, func(_ctx context.Context, cli npool.MiddlewareClient) (cruder.Any, error) { 55 resp, err := cli.GetCurrencies(ctx, &npool.GetCurrenciesRequest{ 56 Conds: conds, 57 Offset: offset, 58 Limit: limit, 59 }) 60 if err != nil { 61 return nil, err 62 } 63 64 total = resp.Total 65 66 return resp.Infos, nil 67 }) 68 if err != nil { 69 return nil, 0, err 70 } 71 return infos.([]*npool.Currency), total, nil 72 } 73 74 func GetCurrencyOnly(ctx context.Context, conds *npool.Conds) (*npool.Currency, error) { 75 infos, err := withCRUD(ctx, func(_ctx context.Context, cli npool.MiddlewareClient) (cruder.Any, error) { 76 const singleRowLimit = 1 77 resp, err := cli.GetCurrencies(ctx, &npool.GetCurrenciesRequest{ 78 Conds: conds, 79 Offset: 0, 80 Limit: singleRowLimit, 81 }) 82 if err != nil { 83 return nil, err 84 } 85 return resp.Infos, nil 86 }) 87 if err != nil { 88 return nil, err 89 } 90 if len(infos.([]*npool.Currency)) == 0 { 91 return nil, nil 92 } 93 return infos.([]*npool.Currency)[0], nil 94 }