OSDN Git Service

Add txfeed commands to cobra & Change accesstoken rpc to jsend format (#140)
authoryahtoo <yahtoo.ma@gmail.com>
Wed, 29 Nov 2017 01:48:38 +0000 (09:48 +0800)
committerPaladz <yzhu101@uottawa.ca>
Wed, 29 Nov 2017 01:48:38 +0000 (09:48 +0800)
* Add txfeed comands to cobra

* Change accesstoken rpc to jsend format

* Change accesstoken handler  from  "a" to "br"

blockchain/accesstokens.go
blockchain/jsend.go [new file with mode: 0644]
blockchain/txfeeds.go
cmd/cobra/commands/accesstoken.go
cmd/cobra/commands/bytomcli.go
cmd/cobra/commands/txfeed.go [new file with mode: 0644]

index 38a9a08..47da499 100644 (file)
@@ -3,51 +3,49 @@ package blockchain
 import (
        "context"
        "encoding/hex"
-       "encoding/json"
 
        "github.com/bytom/errors"
 )
 
 var errCurrentToken = errors.New("token cannot delete itself")
 
-func (a *BlockchainReactor) createAccessToken(ctx context.Context, x struct{ ID, Type string }) interface{} {
-       token, err := a.accessTokens.Create(ctx, x.ID, x.Type)
+func (br *BlockchainReactor) createAccessToken(ctx context.Context, x struct{ ID, Type string }) interface{} {
+       token, err := br.accessTokens.Create(ctx, x.ID, x.Type)
        if err != nil {
-               return err.Error()
+               return jsendWrapper(nil, ERROR, err.Error())
        }
 
-       return token
+       return jsendWrapper(token, SUCCESS, "")
 }
 
-func (a *BlockchainReactor) listAccessTokens(ctx context.Context) interface{} {
-       tokens, err := a.accessTokens.List(ctx)
+func (br *BlockchainReactor) listAccessTokens(ctx context.Context) interface{} {
+       tokens, err := br.accessTokens.List(ctx)
        if err != nil {
-               return err.Error()
+               return jsendWrapper(nil, ERROR, err.Error())
        }
 
-       result, err := json.Marshal(tokens)
-       if err != nil {
-               return err.Error()
-       }
-       return string(result)
+       return jsendWrapper(tokens, SUCCESS, "")
 }
 
-func (a *BlockchainReactor) deleteAccessToken(ctx context.Context, x struct{ ID, Token string }) interface{} {
+func (br *BlockchainReactor) deleteAccessToken(ctx context.Context, x struct{ ID, Token string }) interface{} {
        //TODO Add delete permission verify.
-       if err := a.accessTokens.Delete(ctx, x.ID); err != nil {
-               return err.Error()
+       if err := br.accessTokens.Delete(ctx, x.ID); err != nil {
+               return jsendWrapper(nil, ERROR, err.Error())
        }
-       return "success!"
+       return jsendWrapper("success", SUCCESS, "")
 }
 
-func (a *BlockchainReactor) checkAccessToken(ctx context.Context, x struct{ ID, Secret string }) interface{} {
+func (br *BlockchainReactor) checkAccessToken(ctx context.Context, x struct{ ID, Secret string }) interface{} {
        secret, err := hex.DecodeString(x.Secret)
        if err != nil {
-               return err.Error()
+               return jsendWrapper(nil, ERROR, err.Error())
        }
-       result, err := a.accessTokens.Check(ctx, x.ID, secret)
+       result, err := br.accessTokens.Check(ctx, x.ID, secret)
        if err != nil {
-               return err.Error()
+               return jsendWrapper(nil, ERROR, err.Error())
+       }
+       if result == true {
+               return jsendWrapper("success", SUCCESS, "")
        }
-       return result
+       return jsendWrapper("fail", SUCCESS, "")
 }
diff --git a/blockchain/jsend.go b/blockchain/jsend.go
new file mode 100644 (file)
index 0000000..1e46ad0
--- /dev/null
@@ -0,0 +1,24 @@
+package blockchain
+
+import (
+       "encoding/json"
+)
+
+type jsendResponse struct {
+       Status string      `json:"status,omitempty"`
+       Msg    string      `json:"msg,omitempty"`
+       Data   interface{} `json:"data,omitempty"`
+}
+
+func jsendWrapper(data interface{}, status, msg string) []byte {
+       response := &jsendResponse{
+               Status: status,
+               Msg:    msg,
+               Data:   data,
+       }
+       rawResponse, err := json.Marshal(response)
+       if err != nil {
+               return DefaultRawResponse
+       }
+       return rawResponse
+}
index 9b54522..da01161 100644 (file)
@@ -14,17 +14,16 @@ import (
 func (bcr *BlockchainReactor) createTxFeed(ctx context.Context, in struct {
        Alias  string
        Filter string
-}) error {
+}) interface{} {
        if err := bcr.txFeedTracker.Create(ctx, in.Alias, in.Filter); err != nil {
                log.WithField("error", err).Error("Add TxFeed Failed")
-               return err
+               return jsendWrapper(nil, ERROR, err.Error())
        }
-       return nil
+       return jsendWrapper("success", SUCCESS, "")
 }
 
-func (bcr *BlockchainReactor) getTxFeedByAlias(ctx context.Context, filter string) ([]*txfeed.TxFeed, error) {
+func (bcr *BlockchainReactor) getTxFeedByAlias(ctx context.Context, filter string) (*txfeed.TxFeed, error) {
        txFeed := &txfeed.TxFeed{}
-       txFeeds := []*txfeed.TxFeed{}
 
        jf, err := json.Marshal(filter)
        if err != nil {
@@ -39,36 +38,43 @@ func (bcr *BlockchainReactor) getTxFeedByAlias(ctx context.Context, filter strin
        if err := json.Unmarshal(value, txFeed); err != nil {
                return nil, err
        }
-       txFeeds = append(txFeeds, txFeed)
-       return txFeeds, nil
+       return txFeed, nil
 }
 
 // POST /get-transaction-feed
-func (bcr *BlockchainReactor) getTxFeed(ctx context.Context, in requestQuery) interface{} {
-       txfeeds, err := bcr.getTxFeedByAlias(ctx, in.Filter)
+func (bcr *BlockchainReactor) getTxFeed(ctx context.Context, in struct {
+       Alias string `json:"alias,omitempty"`
+}) interface{} {
+       txfeed, err := bcr.getTxFeedByAlias(ctx, in.Alias)
        if err != nil {
-               return err
+               return jsendWrapper(nil, ERROR, err.Error())
        }
-       return txfeeds
-
+       return jsendWrapper(txfeed, SUCCESS, "")
 }
 
 // POST /delete-transaction-feed
 func (bcr *BlockchainReactor) deleteTxFeed(ctx context.Context, in struct {
        Alias string `json:"alias,omitempty"`
-}) error {
-       return bcr.txFeedTracker.Delete(ctx, in.Alias)
+}) interface{} {
+       if err := bcr.txFeedTracker.Delete(ctx, in.Alias); err != nil {
+               return jsendWrapper(nil, ERROR, err.Error())
+       }
+       return jsendWrapper("success", SUCCESS, "")
 }
 
 // POST /update-transaction-feed
 func (bcr *BlockchainReactor) updateTxFeed(ctx context.Context, in struct {
        Alias  string
        Filter string
-}) error {
+}) interface{} {
        if err := bcr.txFeedTracker.Delete(ctx, in.Alias); err != nil {
-               return err
+               return jsendWrapper(nil, ERROR, err.Error())
+       }
+       if err := bcr.txFeedTracker.Create(ctx, in.Alias, in.Filter); err != nil {
+               log.WithField("error", err).Error("Update TxFeed Failed")
+               return jsendWrapper(nil, ERROR, err.Error())
        }
-       return bcr.txFeedTracker.Create(ctx, in.Alias, in.Filter)
+       return jsendWrapper("success", SUCCESS, "")
 }
 
 // txAfterIsBefore returns true if a is before b. It returns an error if either
@@ -109,7 +115,7 @@ func (bcr *BlockchainReactor) getTxFeeds() ([]*txfeed.TxFeed, error) {
 func (bcr *BlockchainReactor) listTxFeeds(ctx context.Context, in requestQuery) interface{} {
        txfeeds, err := bcr.getTxFeeds()
        if err != nil {
-               return err
+               return jsendWrapper(nil, ERROR, err.Error())
        }
-       return txfeeds
+       return jsendWrapper(txfeeds, SUCCESS, "")
 }
index 466c98c..eebfa8d 100644 (file)
@@ -2,7 +2,9 @@ package commands
 
 import (
        "context"
+       "encoding/base64"
        "encoding/json"
+       "fmt"
        "strings"
        "time"
 
@@ -12,11 +14,38 @@ import (
 
 //Token describe the access token.
 type Token struct {
-       ID      string    `json:"id"`
+       ID      string    `json:"id,omitempty"`
        Token   string    `json:"token,omitempty"`
        Type    string    `json:"type,omitempty"`
        Secret  string    `json:"secret,omitempty"`
-       Created time.Time `json:"created_at"`
+       Created time.Time `json:"created_at,omitempty"`
+}
+
+type resp struct {
+       Status string `json:"status,omitempty"`
+       Msg    string `json:"msg,omitempty"`
+       Data   string `json:"data,omitempty"`
+}
+
+type respToken struct {
+       Status string   `json:"status,omitempty"`
+       Msg    string   `json:"msg,omitempty"`
+       Data   []*Token `json:"data,omitempty"`
+}
+
+func parseresp(response interface{}, pattern interface{}) error {
+       data, err := base64.StdEncoding.DecodeString(response.(string))
+       if err != nil {
+               jww.ERROR.Println("response format error")
+               return err
+       }
+
+       if err := json.Unmarshal(data, pattern); err != nil {
+               jww.ERROR.Println("result not json format", err)
+               return err
+       }
+
+       return nil
 }
 
 var createAccessTokenCmd = &cobra.Command{
@@ -36,7 +65,21 @@ var createAccessTokenCmd = &cobra.Command{
                client := mustRPCClient()
                client.Call(context.Background(), "/create-access-token", &token, &response)
 
-               jww.FEEDBACK.Printf("response: %v\n", response)
+               var rawresp resp
+               if err := parseresp(response, &rawresp); err != nil {
+                       jww.ERROR.Println("parse response error")
+                       return
+               }
+
+               if rawresp.Status == "success" {
+                       jww.FEEDBACK.Printf("%v\n", rawresp.Data)
+                       return
+               }
+
+               if rawresp.Status == "error" {
+                       jww.ERROR.Println(rawresp.Msg)
+                       return
+               }
        },
 }
 
@@ -50,17 +93,25 @@ var listAccessTokenCmd = &cobra.Command{
                }
 
                var response interface{}
-               var tokens []Token
                client := mustRPCClient()
                client.Call(context.Background(), "/list-access-token", nil, &response)
 
-               if err := json.Unmarshal([]byte(response.(string)), &tokens); err != nil {
-                       jww.ERROR.Println("result not json format")
+               var rawresp respToken
+               if err := parseresp(response, &rawresp); err != nil {
+                       jww.ERROR.Println("parse response error")
+                       return
+               }
+
+               if rawresp.Status == "success" {
+                       for i, v := range rawresp.Data {
+                               fmt.Println(i, v.Token)
+                       }
                        return
                }
 
-               for i, v := range tokens {
-                       jww.FEEDBACK.Printf("%d %v\n", i, v)
+               if rawresp.Status == "error" {
+                       jww.ERROR.Println(rawresp.Msg)
+                       return
                }
        },
 }
@@ -82,7 +133,22 @@ var deleteAccessTokenCmd = &cobra.Command{
                client := mustRPCClient()
                client.Call(context.Background(), "/delete-access-token", &token, &response)
 
-               jww.FEEDBACK.Printf("response: %v\n", response)
+               var rawresp resp
+
+               if err := parseresp(response, &rawresp); err != nil {
+                       jww.ERROR.Println("parse response error")
+                       return
+               }
+
+               if rawresp.Status == "success" {
+                       jww.FEEDBACK.Printf("%v\n", rawresp.Data)
+                       return
+               }
+
+               if rawresp.Status == "error" {
+                       jww.ERROR.Println(rawresp.Msg)
+                       return
+               }
        },
 }
 
@@ -103,6 +169,21 @@ var checkAccessTokenCmd = &cobra.Command{
                client := mustRPCClient()
                client.Call(context.Background(), "/check-access-token", &token, &response)
 
-               jww.FEEDBACK.Printf("response: %v\n", response)
+               var rawresp resp
+
+               if err := parseresp(response, &rawresp); err != nil {
+                       jww.ERROR.Println("parse response error")
+                       return
+               }
+
+               if rawresp.Status == "success" {
+                       jww.FEEDBACK.Printf("%v\n", rawresp.Data)
+                       return
+               }
+
+               if rawresp.Status == "error" {
+                       jww.ERROR.Println(rawresp.Msg)
+                       return
+               }
        },
 }
index 4f613a8..2a7c5f8 100644 (file)
@@ -119,6 +119,12 @@ func AddCommands() {
        BytomcliCmd.AddCommand(deleteAccessTokenCmd)
        BytomcliCmd.AddCommand(checkAccessTokenCmd)
 
+       BytomcliCmd.AddCommand(createTransactionFeedCmd)
+       BytomcliCmd.AddCommand(listTransactionFeedsCmd)
+       BytomcliCmd.AddCommand(deleteTransactionFeedCmd)
+       BytomcliCmd.AddCommand(getTransactionFeedCmd)
+       BytomcliCmd.AddCommand(updateTransactionFeedCmd)
+
        BytomcliCmd.AddCommand(versionCmd)
 }
 
diff --git a/cmd/cobra/commands/txfeed.go b/cmd/cobra/commands/txfeed.go
new file mode 100644 (file)
index 0000000..6eae8c0
--- /dev/null
@@ -0,0 +1,204 @@
+package commands
+
+import (
+       "context"
+       "fmt"
+
+       "github.com/spf13/cobra"
+       jww "github.com/spf13/jwalterweatherman"
+)
+
+type txFeed struct {
+       Alias  string `json:"alias"`
+       Filter string `json:"filter,omitempty"`
+}
+
+type respArrayTxFeed struct {
+       Status string    `json:"status,omitempty"`
+       Msg    string    `json:"msg,omitempty"`
+       Data   []*txFeed `json:"data,omitempty"`
+}
+
+type respTxFeed struct {
+       Status string `json:"status,omitempty"`
+       Msg    string `json:"msg,omitempty"`
+       Data   txFeed `json:"data,omitempty"`
+}
+
+var createTransactionFeedCmd = &cobra.Command{
+       Use:   "create-transaction-feed",
+       Short: "Create a transaction feed filter",
+       Run: func(cmd *cobra.Command, args []string) {
+               if len(args) != 2 {
+                       jww.ERROR.Println("create-transaction-feed needs 2 args")
+                       return
+               }
+
+               var in txFeed
+               in.Alias = args[0]
+               in.Filter = args[1]
+
+               var response interface{}
+
+               client := mustRPCClient()
+               client.Call(context.Background(), "/create-transaction-feed", &in, &response)
+
+               var rawresp resp
+
+               if err := parseresp(response, &rawresp); err != nil {
+                       jww.ERROR.Println("parse response error")
+                       return
+               }
+
+               if rawresp.Status == "success" {
+                       jww.FEEDBACK.Printf("%v\n", rawresp.Data)
+                       return
+               }
+
+               if rawresp.Status == "error" {
+                       jww.ERROR.Println(rawresp.Msg)
+                       return
+               }
+       },
+}
+
+var listTransactionFeedsCmd = &cobra.Command{
+       Use:   "list-transaction-feeds",
+       Short: "list all of transaction feeds",
+       Run: func(cmd *cobra.Command, args []string) {
+               if len(args) != 0 {
+                       jww.ERROR.Println("list-transaction-feeds takes no args")
+                       return
+               }
+
+               var in requestQuery
+               var response interface{}
+
+               client := mustRPCClient()
+               client.Call(context.Background(), "/list-transaction-feeds", in, &response)
+
+               var rawresp respArrayTxFeed
+               if err := parseresp(response, &rawresp); err != nil {
+                       jww.ERROR.Println("parse response error")
+                       return
+               }
+
+               if rawresp.Status == "success" {
+                       for i, v := range rawresp.Data {
+                               fmt.Println(i, v.Alias, v.Filter)
+                       }
+                       return
+               }
+
+               if rawresp.Status == "error" {
+                       jww.ERROR.Println(rawresp.Msg)
+                       return
+               }
+       },
+}
+
+var deleteTransactionFeedCmd = &cobra.Command{
+       Use:   "delete-transaction-feed",
+       Short: "Delete a transaction feed filter",
+       Run: func(cmd *cobra.Command, args []string) {
+               if len(args) != 1 {
+                       jww.ERROR.Println("delete-transaction-feed needs 1 args")
+                       return
+               }
+
+               var in txFeed
+               in.Alias = args[0]
+
+               var response interface{}
+
+               client := mustRPCClient()
+               client.Call(context.Background(), "/delete-transaction-feed", &in, &response)
+
+               var rawresp resp
+               if err := parseresp(response, &rawresp); err != nil {
+                       jww.ERROR.Println("parse response error")
+                       return
+               }
+
+               if rawresp.Status == "success" {
+                       jww.FEEDBACK.Printf("%v\n", rawresp.Data)
+                       return
+               }
+
+               if rawresp.Status == "error" {
+                       jww.ERROR.Println(rawresp.Msg)
+                       return
+               }
+       },
+}
+
+var getTransactionFeedCmd = &cobra.Command{
+       Use:   "get-transaction-feed",
+       Short: "get a transaction feed by alias",
+       Run: func(cmd *cobra.Command, args []string) {
+               if len(args) != 1 {
+                       jww.ERROR.Println("get-transaction-feed needs 1 args")
+                       return
+               }
+
+               var in txFeed
+               in.Alias = args[0]
+               var response interface{}
+
+               client := mustRPCClient()
+               client.Call(context.Background(), "/get-transaction-feed", &in, &response)
+
+               var rawresp respTxFeed
+
+               if err := parseresp(response, &rawresp); err != nil {
+                       jww.ERROR.Println("parse response error")
+                       return
+               }
+
+               if rawresp.Status == "success" {
+                       fmt.Println(rawresp.Data)
+                       return
+               }
+
+               if rawresp.Status == "error" {
+                       jww.ERROR.Println(rawresp.Msg)
+                       return
+               }
+       },
+}
+
+var updateTransactionFeedCmd = &cobra.Command{
+       Use:   "update-transaction-feed",
+       Short: "Update transaction feed",
+       Run: func(cmd *cobra.Command, args []string) {
+               if len(args) != 2 {
+                       jww.ERROR.Println("update-transaction-feed needs 2 args")
+                       return
+               }
+
+               var in txFeed
+               in.Alias = args[0]
+               in.Filter = args[1]
+
+               var response interface{}
+
+               client := mustRPCClient()
+               client.Call(context.Background(), "/update-transaction-feed", &in, &response)
+
+               var rawresp resp
+               if err := parseresp(response, &rawresp); err != nil {
+                       jww.ERROR.Println("parse response error")
+                       return
+               }
+
+               if rawresp.Status == "success" {
+                       jww.FEEDBACK.Printf("%v\n", rawresp.Data)
+                       return
+               }
+
+               if rawresp.Status == "error" {
+                       jww.ERROR.Println(rawresp.Msg)
+                       return
+               }
+       },
+}