Skip to content

Commit

Permalink
Support coercion on the "number" type
Browse files Browse the repository at this point in the history
Supports coercion on the JSON schema "number" type like we do already
for booleans and integers.
  • Loading branch information
brandur committed Aug 24, 2017
1 parent 82670b0 commit 22fce71
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
9 changes: 9 additions & 0 deletions param/coercer/coercer.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,13 @@ func CoerceParams(schema *spec.JSONSchema, data map[string]interface{}) {
valInt = 0
}
data[key] = valInt

case hasType(subSchema, numberType):
valFloat, err := strconv.ParseFloat(valStr, 64)
if err != nil {
valFloat = 0.0
}
data[key] = valFloat
}
}
}
Expand All @@ -57,6 +64,8 @@ const booleanType = "boolean"
// integerType is the name of the integer type in a JSON schema.
const integerType = "integer"

const numberType = "number"

func hasType(schema *spec.JSONSchema, targetTypeStr string) bool {
for _, typeStr := range schema.Type {
if typeStr == targetTypeStr {
Expand Down
12 changes: 12 additions & 0 deletions param/coercer/coercer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,18 @@ func TestCoerceParams_IntegerCoercion(t *testing.T) {
assert.Equal(t, 123, data["intkey"])
}

func TestCoerceParams_NumberCoercion(t *testing.T) {
schema := &spec.JSONSchema{Properties: map[string]*spec.JSONSchema{
"numberkey": {Type: []string{numberType}},
}}
data := map[string]interface{}{
"numberkey": "123.45",
}

CoerceParams(schema, data)
assert.Equal(t, 123.45, data["numberkey"])
}

func TestCoerceParams_Recursion(t *testing.T) {
schema := &spec.JSONSchema{Properties: map[string]*spec.JSONSchema{
"mapkey": {Properties: map[string]*spec.JSONSchema{
Expand Down

0 comments on commit 22fce71

Please sign in to comment.