Skip to content

Commit 94a121c

Browse files
committed
Support validation for the JSON field name
1 parent 85dab08 commit 94a121c

7 files changed

+2973
-4
lines changed

internal/protoschema/jsonschema/jsonschema.go

+21-2
Original file line numberDiff line numberDiff line change
@@ -72,16 +72,35 @@ func (p *jsonSchemaGenerator) generateDefault(result map[string]interface{}, des
7272
result["type"] = jsObject
7373
p.setDescription(desc, result)
7474
var properties = make(map[string]interface{})
75+
var patternProperties = make(map[string]interface{})
7576
for i := range desc.Fields().Len() {
7677
field := desc.Fields().Get(i)
7778
if p.shouldIgnoreField(field) {
7879
continue
7980
}
80-
name := string(field.Name())
81-
properties[name] = p.generateField(field)
81+
82+
// Generate the schema
83+
fieldSchema := p.generateField(field)
84+
85+
// TODO: Add an option to include custom alias.
86+
aliases := make([]string, 0, 1)
87+
88+
// TODO: Optionally make the json name the 'primary' name.
89+
properties[string(field.Name())] = fieldSchema
90+
if field.JSONName() != string(field.Name()) {
91+
aliases = append(aliases, field.JSONName())
92+
}
93+
94+
if len(aliases) > 0 {
95+
pattern := "^(" + strings.Join(aliases, "|") + ")$"
96+
patternProperties[pattern] = fieldSchema
97+
}
8298
}
8399
result["properties"] = properties
84100
result["additionalProperties"] = false
101+
if len(patternProperties) > 0 {
102+
result["patternProperties"] = patternProperties
103+
}
85104
}
86105

87106
func (p *jsonSchemaGenerator) setDescription(desc protoreflect.Descriptor, result map[string]interface{}) {

internal/testdata/codegenrequest/input.json

+1-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

internal/testdata/jsonschema-doc/test.TestAllTypes.yaml

+3-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

internal/testdata/jsonschema/buf.protoschema.test.v1.CustomOptions.schema.json

+13
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

internal/testdata/jsonschema/buf.protoschema.test.v1.IgnoreField.schema.json

+5
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

internal/testdata/jsonschema/buf.protoschema.test.v1.NestedReference.schema.json

+5
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)