Skip to content

Commit

Permalink
Fix panic from bare string default (#53)
Browse files Browse the repository at this point in the history
* Initial commit

* Removing an if condition; linter

* Break up if statements into functions

* Reword second error message
  • Loading branch information
jdowni000 authored Sep 14, 2023
1 parent a90b78b commit 8194670
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion schema/object.go
Original file line number Diff line number Diff line change
Expand Up @@ -690,7 +690,10 @@ func extractObjectDefaultValues(properties map[string]*PropertySchema) map[strin
for propertyID, property := range properties {
if property.Default() != nil {
var value any
if err := json.Unmarshal([]byte(*property.Default()), &value); err != nil {
defaultValue := *property.Default()
propertyType := property.TypeID()
err := jsonUnmarshal(defaultValue, &value, propertyType)
if err != nil {
panic(BadArgumentError{
Message: fmt.Sprintf("Default value for property %s is not a valid JSON", propertyID),
Cause: err,
Expand All @@ -702,6 +705,22 @@ func extractObjectDefaultValues(properties map[string]*PropertySchema) map[strin
return defaultValues
}

func jsonUnmarshal(defaultValue string, value any, propertryType TypeID) error {
err := json.Unmarshal([]byte(defaultValue), &value)
if err != nil && propertryType == "string" {
// attempt to fix yaml string to valid JSON
defaultValueTypeString := ("\"" + defaultValue + "\"")
err2 := json.Unmarshal([]byte(defaultValueTypeString), &value)
if err2 != nil {
return fmt.Errorf("{%s} additional attempt to format string with additional quotes failed:{%s}",
err.Error(), err2.Error())
} else {
return nil
}
}
return err
}

func buildObjectFieldCache[T any](properties map[string]*PropertySchema) map[string]reflect.StructField {
var defaultValue T
fieldCache := make(map[string]reflect.StructField, len(properties))
Expand Down

0 comments on commit 8194670

Please sign in to comment.