Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Reflector.Requirer to support custom struct field requiring #88

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

funte
Copy link

@funte funte commented Jul 29, 2023

Examples:

package main

import (
	"fmt"
	"reflect"

	"github.com/invopop/jsonschema"
)

type OptionBase struct {
	A int    `json:"a" jsonschema:"required"`
	B string `json:"b" jsonschema:"required"`
}

type OptionChild struct {
	*OptionBase

	C bool `json:"c" jsonschema:"required"`
}

func main() {
	r := jsonschema.Reflector{}
	r.RequiredFromJSONSchemaTags = true
	if s, err := r.Reflect(OptionBase{}).MarshalJSON(); err != nil {
		fmt.Println("failed to marshal OptionBase json schema, err=", err)
	} else {
		// Print OptionBase json schema, all struct fields should be required.
		fmt.Println(string(s))
	}

	// In OptionChild, cancel all requirings of OptionBase struct fields, just keep'C'.
	r.Requirer = func(f reflect.StructField, b bool) bool {
		return f.Name == "C"
	}
	if s, err := r.Reflect(OptionChild{}).MarshalJSON(); err != nil {
		fmt.Println("failed to marshal OptionChild json schema, err=", err)
	} else {
		// Print OptionChild json schema, only struct field 'C' should be required.
		fmt.Println(string(s))
	}
}

@samlown
Copy link
Contributor

samlown commented Sep 6, 2023

Would this also be achieved by #90?

@samlown samlown added the question Further information is requested label Sep 6, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants