cosmos-sdk/baseapp/router.go

77 lines
1.8 KiB
Go
Raw Normal View History

package baseapp
2018-01-12 13:59:19 -08:00
import (
2018-03-27 12:46:06 -07:00
"encoding/json"
"fmt"
2018-01-12 13:59:19 -08:00
"regexp"
sdk "github.com/cosmos/cosmos-sdk/types"
)
2018-02-16 16:52:07 -08:00
// Router provides handlers for each transaction type.
type Router interface {
AddRoute(r string, h sdk.Handler, i sdk.InitGenesis) (rtr Router)
2018-01-12 13:59:19 -08:00
Route(path string) (h sdk.Handler)
2018-03-27 12:46:06 -07:00
InitGenesis(ctx sdk.Context, data map[string]json.RawMessage) error
}
// map a transaction type to a handler and an initgenesis function
type route struct {
r string
2018-01-12 13:59:19 -08:00
h sdk.Handler
i sdk.InitGenesis
}
type router struct {
routes []route
}
// nolint
// NewRouter - create new router
// TODO either make Function unexported or make return type (router) Exported
2018-01-15 17:38:56 -08:00
func NewRouter() *router {
return &router{
2018-01-12 13:59:19 -08:00
routes: make([]route, 0),
}
}
var isAlpha = regexp.MustCompile(`^[a-zA-Z]+$`).MatchString
// AddRoute - TODO add description
func (rtr *router) AddRoute(r string, h sdk.Handler, i sdk.InitGenesis) Router {
if !isAlpha(r) {
panic("route expressions can only contain alphanumeric characters")
}
rtr.routes = append(rtr.routes, route{r, h, i})
return rtr
}
// Route - TODO add description
2018-03-27 12:46:06 -07:00
// TODO handle expressive matches.
2018-01-15 17:38:56 -08:00
func (rtr *router) Route(path string) (h sdk.Handler) {
for _, route := range rtr.routes {
2018-03-27 12:46:06 -07:00
if route.r == path {
return route.h
}
}
return nil
}
2018-03-27 12:46:06 -07:00
// InitGenesis - call `InitGenesis`, where specified, for all routes
// Return the first error if any, otherwise nil
func (rtr *router) InitGenesis(ctx sdk.Context, data map[string]json.RawMessage) error {
for _, route := range rtr.routes {
2018-03-27 12:46:06 -07:00
if route.i != nil {
encoded, found := data[route.r]
if !found {
return sdk.ErrGenesisParse(fmt.Sprintf("Expected module genesis information for module %s but it was not present", route.r))
}
if err := route.i(ctx, encoded); err != nil {
return err
}
}
}
return nil
}