Added candidate list REST query handler

This commit is contained in:
Matt Bell
2018-05-25 09:32:37 +09:00
parent 10056d36d1
commit 074dfd7920
2 changed files with 42 additions and 6 deletions
+40 -5
View File
@@ -6,7 +6,6 @@ import (
"net/http"
"github.com/gorilla/mux"
"github.com/tendermint/go-crypto/keys"
"github.com/cosmos/cosmos-sdk/client/context"
sdk "github.com/cosmos/cosmos-sdk/types"
@@ -14,12 +13,13 @@ import (
"github.com/cosmos/cosmos-sdk/x/stake"
)
func registerQueryRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec, kb keys.Keybase) {
r.HandleFunc("/stake/{delegator}/bonding_status/{candidate}", bondingStatusHandlerFn("stake", cdc, kb, ctx)).Methods("GET")
func registerQueryRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec) {
r.HandleFunc("/stake/{delegator}/bonding_status/{candidate}", bondingStatusHandlerFn("stake", cdc, ctx)).Methods("GET")
r.HandleFunc("/stake/candidates", candidatesHandlerFn("stake", cdc, ctx)).Methods("GET")
}
// BondingStatusHandlerFn - http request handler to query delegator bonding status
func bondingStatusHandlerFn(storeName string, cdc *wire.Codec, kb keys.Keybase, ctx context.CoreContext) http.HandlerFunc {
// bondingStatusHandlerFn - http request handler to query delegator bonding status
func bondingStatusHandlerFn(storeName string, cdc *wire.Codec, ctx context.CoreContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// read parameters
vars := mux.Vars(r)
@@ -75,3 +75,38 @@ func bondingStatusHandlerFn(storeName string, cdc *wire.Codec, kb keys.Keybase,
w.Write(output)
}
}
// candidatesHandlerFn - http request handler to query list of candidates
func candidatesHandlerFn(storeName string, cdc *wire.Codec, ctx context.CoreContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
res, err := ctx.Query(stake.CandidatesKey, storeName)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(fmt.Sprintf("Couldn't query bond. Error: %s", err.Error())))
return
}
// the query will return empty if there is no data for this bond
if len(res) == 0 {
w.WriteHeader(http.StatusNoContent)
return
}
var candidates []stake.Candidate
err = cdc.UnmarshalBinary(res, &candidates)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(fmt.Sprintf("Couldn't decode candidates. Error: %s", err.Error())))
return
}
output, err := cdc.MarshalJSON(candidates)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
w.Write(output)
}
}
+2 -1
View File
@@ -8,7 +8,8 @@ import (
"github.com/cosmos/cosmos-sdk/wire"
)
// RegisterRoutes registers staking-related REST handlers to a router
func RegisterRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec, kb keys.Keybase) {
registerQueryRoutes(ctx, r, cdc, kb)
registerQueryRoutes(ctx, r, cdc)
registerTxRoutes(ctx, r, cdc, kb)
}