From be0e3459e4c130ccf94398c62b3b060fbbc83aa0 Mon Sep 17 00:00:00 2001 From: Samuele Date: Thu, 12 Sep 2024 14:52:54 +0200 Subject: [PATCH] fix(utils): do not fill empty records (#467) follow up of: https://github.com/Kong/go-kong/pull/466, prevent unset records to be filled with empty tables: {} --- kong/utils.go | 7 +++++- kong/utils_test.go | 56 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/kong/utils.go b/kong/utils.go index 575f7526..65c42654 100644 --- a/kong/utils.go +++ b/kong/utils.go @@ -355,7 +355,12 @@ func fillConfigRecord(schema gjson.Result, config Configuration, opts FillRecord fieldConfig = subConfig.(map[string]interface{}) } newSubConfig := fillConfigRecord(value.Get(fname), fieldConfig, opts) - res[fname] = map[string]interface{}(newSubConfig) + // When we are not filling defaults, only assign the subconfig if it's not empty. + // This is to avoid having records that are assigned empty map values when defaults + // are not supposed to be filled. + if opts.FillDefaults || len(newSubConfig) > 0 { + res[fname] = map[string]interface{}(newSubConfig) + } return true } diff --git a/kong/utils_test.go b/kong/utils_test.go index db36c454..da0e96b7 100644 --- a/kong/utils_test.go +++ b/kong/utils_test.go @@ -1971,6 +1971,48 @@ const fillConfigRecordTestSchemaWithAutoFields = `{ } ` +const fillConfigRecordTestSchemaWithRecord = `{ + "fields": { + "config": { + "type": "record", + "fields": [ + { + "some_record": { + "required": true, + "fields": [ + { + "some_field": { + "default": "kong", + "type": "string" + } + } + ], + "type": "record" + } + }, + { + "some_other_record": { + "fields": [ + { + "some_field": { + "type": "string" + } + } + ], + "type": "record" + } + }, + { + "string_1": { + "type": "string", + } + } + ] + } + } +} +` + func Test_fillConfigRecord_shorthand_fields(t *testing.T) { tests := []struct { name string @@ -2098,6 +2140,20 @@ func Test_fillConfigRecord_auto_only(t *testing.T) { // defalt_string missing }, }, + { + name: "not passing record field leaves field unset", + schema: gjson.Parse(fillConfigRecordTestSchemaWithRecord), + config: Configuration{ + // some_record missing + "some_other_record": map[string]any{}, // explicitly set to empty record + "string_1": "abc", + }, + expected: Configuration{ + // some_record was not filled + "some_other_record": map[string]any{}, // empty record remained unchanged + "string_1": "abc", + }, + }, } for _, tc := range tests {