Skip to content

Commit

Permalink
Add ParentSchema to intercept prop params (#97)
Browse files Browse the repository at this point in the history
  • Loading branch information
vearutop authored Sep 29, 2023
1 parent f6cad16 commit 9eb11d1
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 4 deletions.
1 change: 1 addition & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ type InterceptPropParams struct {
Name string
Field reflect.StructField
PropertySchema *Schema
ParentSchema *Schema
Processed bool
}

Expand Down
10 changes: 6 additions & 4 deletions reflect.go
Original file line number Diff line number Diff line change
Expand Up @@ -957,10 +957,11 @@ func (r *Reflector) walkProperties(v reflect.Value, parent *Schema, rc *ReflectC

if rc.interceptProp != nil {
if err := rc.interceptProp(InterceptPropParams{
Context: rc,
Path: rc.Path,
Name: propName,
Field: field,
Context: rc,
Path: rc.Path,
Name: propName,
Field: field,
ParentSchema: parent,
}); err != nil {
if errors.Is(err, ErrSkipProperty) {
rc.Path = rc.Path[:len(rc.Path)-1]
Expand Down Expand Up @@ -1026,6 +1027,7 @@ func (r *Reflector) walkProperties(v reflect.Value, parent *Schema, rc *ReflectC
Name: propName,
Field: field,
PropertySchema: &propertySchema,
ParentSchema: parent,
Processed: true,
}); err != nil {
if errors.Is(err, ErrSkipProperty) {
Expand Down
45 changes: 45 additions & 0 deletions reflect_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1679,3 +1679,48 @@ func TestReflector_Reflect_nullable(t *testing.T) {
"type":"object"
}`, s)
}

func TestReflector_Reflect_customTags(t *testing.T) {
r := jsonschema.Reflector{}

type My struct {
Foo string `json:"foo" validate:"required" description:"This is foo."`
}

type Parent struct {
MySlice []*My `json:"my,omitempty" validate:"required" description:"The required array."`
}

s, err := r.Reflect(Parent{}, jsonschema.InterceptProp(func(params jsonschema.InterceptPropParams) error {
if !params.Processed {
return nil
}

if v, ok := params.Field.Tag.Lookup("validate"); ok {
if strings.Contains(v, "required") {
params.ParentSchema.Required = append(params.ParentSchema.Required, params.Name)
}
}

return nil
}))
require.NoError(t, err)

assertjson.EqMarshal(t, `{
"required":["my"],
"definitions":{
"JsonschemaGoTestMy":{
"required":["foo"],
"properties":{"foo":{"description":"This is foo.","type":"string"}},
"type":"object"
}
},
"properties":{
"my":{
"description":"The required array.",
"items":{"$ref":"#/definitions/JsonschemaGoTestMy"},"type":"array"
}
},
"type":"object"
}`, s)
}

0 comments on commit 9eb11d1

Please sign in to comment.