jsonschema icon indicating copy to clipboard operation
jsonschema copied to clipboard

Document how to use `SchemaRegistry`

Open ieure opened this issue 3 years ago • 2 comments

I have a schema broken into a few components, common.json, input.json, and stored.json; input and stored both reference types from common.

I'm loading all the schemas in my package's init():

var (
	SchemaCommon *jsonschema.Schema
	SchemaInput  *jsonschema.Schema
	SchemaStored *jsonschema.Schema
)

func init() {
	SchemaCommon = jsonschema.Must(schemaCommon)
	SchemaInput = jsonschema.Must(schemaInput)
	SchemaStored = jsonschema.Must(schemaStored)
}

When I try to validate a document against the input or stored schemas, it gives me a "failed to resolve schema for ref" error.

So, okay, it looks like I have to register the schemas in the schema registry for jsonschema to know about them. That's fine, but the obvious Register() / Get() mechanism doesn't work:

func init() {
	SchemaCommon = jsonschema.Must(schemaCommon)
	SchemaInput = jsonschema.Must(schemaInput)
	SchemaStored = jsonschema.Must(schemaStored)

	reg := jsonschema.GetSchemaRegistry()
	reg.Register(SchemaCommon)
	s := reg.Get(context.Background(), "https://example.com/schema/1.0/common.json")
	if s == nil {
		panic("Schema wasn't registered")
	}
}
panic: Schema wasn't registered

The ID I'm supplying is the value of the $id property at the top level of common.json.

Similarly, if I use RegisterLocal() / GetLocal(), I get a nil schema back as well.

How is this supposed to work?

Specific things it would be good to document:

  • What's the difference between the "local" and "top level" contexts?
  • What's the difference between Get() and GetKnown()? What makes a schema "known?"
  • What's the difference between Schema.Register() and SchemaRegistry.Register()? What cases should each be used in?

ieure avatar Jan 06 '22 18:01 ieure

Okay, it looks like this is the thing to do:

func init() {
	reg := jsonschema.GetSchemaRegistry()
	jsonschema.Must(schemaCommon).Register("", reg)
	jsonschema.Must(schemaInput).Register("", reg)
	jsonschema.Must(schemaStored).Register("", reg)
}

This is extremely non-obvious, and it's kind of wacky that you have to provide an empty URI string.

ieure avatar Jan 06 '22 19:01 ieure

Okay, nope. That successfully registers the schema, instead of silently doing nothing at all, but actually validating still breaks with:

failed to resolve schema for ref

I guess I'll just duplicate the common stuff into the other two schemas for now, but I'd really like to know how to split things up.

ieure avatar Jan 06 '22 19:01 ieure