Skip to content

Commit

Permalink
generalize block payload validation
Browse files Browse the repository at this point in the history
  • Loading branch information
Intizar-T committed May 28, 2024
1 parent ce513da commit 6dd356b
Showing 1 changed file with 15 additions and 10 deletions.
25 changes: 15 additions & 10 deletions api/blocks/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,19 @@ type BlocksModel struct {
Blocks []int64 `db:"blocks" json:"blocks" validate:"dive,isZeroOrPositive"`
}

var validate *validator.Validate

func init() {
validate = validator.New()
validate.RegisterValidation("isZeroOrPositive", func(fl validator.FieldLevel) bool {
return fl.Field().Int() >= 0
})
}

func validateBlockPayload(payload interface{}) error {
return validate.Struct(payload)
}

func getObservedBlock(c *fiber.Ctx) error {
service := c.Query("service")
if service == "" {
Expand All @@ -37,11 +50,7 @@ func upsertObservedBlock(c *fiber.Ctx) error {
return err
}

validate := validator.New()
validate.RegisterValidation("isZeroOrPositive", func(fl validator.FieldLevel) bool {
return fl.Field().Int() >= 0
})
if err := validate.Struct(payload); err != nil {
if err := validateBlockPayload(payload); err != nil {
return err
}

Expand Down Expand Up @@ -77,11 +86,7 @@ func insertUnprocessedBlocks(c *fiber.Ctx) error {
return err
}

validate := validator.New()
validate.RegisterValidation("isZeroOrPositive", func(fl validator.FieldLevel) bool {
return fl.Field().Int() >= 0
})
if err := validate.Struct(payload); err != nil {
if err := validateBlockPayload(payload); err != nil {
return err
}

Expand Down

0 comments on commit 6dd356b

Please sign in to comment.