Skip to content

Commit

Permalink
fix: Use field name in json type schema if json tag is missing
Browse files Browse the repository at this point in the history
  • Loading branch information
erezrokah committed Dec 18, 2024
1 parent b12dc10 commit 3d025a2
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
12 changes: 12 additions & 0 deletions transformers/name.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,16 @@ func DefaultNameTransformer(field reflect.StructField) (string, error) {
return defaultCaser.ToSnake(name), nil
}

func JsonTagOrFieldName(field reflect.StructField) (string, error) {

Check failure on line 29 in transformers/name.go

View workflow job for this annotation

GitHub Actions / Lint with GolangCI

var-naming: func JsonTagOrFieldName should be JSONTagOrFieldName (revive)
name := field.Name
if jsonTag := strings.Split(field.Tag.Get("json"), ",")[0]; len(jsonTag) > 0 {
// return empty string if the field is not related api response
if jsonTag == "-" {
return "", nil
}
return jsonTag, nil
}
return name, nil
}

var _ NameTransformer = DefaultNameTransformer
2 changes: 1 addition & 1 deletion transformers/struct.go
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,7 @@ func (t *structTransformer) fieldToJSONSchema(field reflect.StructField, depth i
if !structField.IsExported() || isTypeIgnored(structField.Type) {
continue
}
name, err := t.nameTransformer(structField)
name, err := JsonTagOrFieldName(structField)
if err != nil {
continue
}
Expand Down
19 changes: 19 additions & 0 deletions transformers/struct_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"github.com/cloudquery/plugin-sdk/v4/schema"
"github.com/cloudquery/plugin-sdk/v4/types"
"github.com/google/go-cmp/cmp"
"github.com/stretchr/testify/require"
)

type (
Expand Down Expand Up @@ -665,6 +666,23 @@ func TestJSONTypeSchema(t *testing.T) {
"item": `{"exported":"utf8"}`,
},
},
{
name: "no json tags",
testStruct: struct {
Tags map[string]string
Item struct {
Name string
Tags map[string]string
FlatItems []string
ComplexItems []struct {
Name string
}
}
}{},
want: map[string]string{
"item": `{"ComplexItems":[{"Name":"utf8"}],"FlatItems":["utf8"],"Name":"utf8","Tags":{"utf8":"utf8"}}`,
},
},
}

for _, tt := range tests {
Expand All @@ -684,6 +702,7 @@ func TestJSONTypeSchema(t *testing.T) {
}
for col, schema := range tt.want {
column := table.Column(col)
require.NotNil(t, column, "column %q not found", col)
if diff := cmp.Diff(column.TypeSchema, schema); diff != "" {
t.Fatalf("table does not match expected. diff (-got, +want): %v", diff)
}
Expand Down

0 comments on commit 3d025a2

Please sign in to comment.