schema

package
v0.20.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 29, 2024 License: Apache-2.0 Imports: 12 Imported by: 13

README

schema 👍

GoDoc Codecov Go Report Card Version

Simplified JSON-Schema

This is a simplified, minimal implementation of JSON-Schema that is fast and has an easy API. If you're looking for a complete, rigorous implementation of JSON-Schema, you should try another tool.

What it Does

This library implements a sub-set of the JSON-Schema specification

What's Included
  • Unmarshal schema from JSON
  • Array, Boolean, Integer, Number, Object, and String type validators.
  • Custom Format rules
  • Happy API for accessing schema information, and walking a schema tree with a JSON-Pointer

Schemas can also get/set data from a compliant data structure. This is helpful when dealing with dynamic data (like form inputs to a dynamic CMS) that may not be known at compile time.

What's Left Out
  • References
  • Loading remote Schemas by URI.

How It Works

Schema now requires data structures to implement Getter/Setter interfaces to expose the data inside of them. While this is a larger code requirement on client libraries, it means that schema has a type-safe way of getting to dynamic data. There are several examples in the test cases, and the mapof and sliceof libraries in Rosetta also implement these interfaces fully.

Here's a quick example:

type MyStruct struct {
	Name string
	Email string
	Age int
}

func (m MyStruct) GetStringOK(path string) (string, bool) {
	switch path {
	case "name":
		return m.Name, true
	case "email":
		return m.Email, true
	default:
		return "", false
	}
}

func (m *MyStruct) SetStringOK(path string, value string) bool {
	switch path {
	case "name":
		m.Name = value
		return true

	case "email":
		m.Email = value
		return true
	default:
		return false
	}
}

Additional interfaces enable schemas to traverse nested structures and arrays.

Pull Requests Welcome

This library is a work in progress, and will benefit from your experience reports, use cases, and contributions. If you have an idea for making Rosetta better, send in a pull request. We're all in this together! 👍

Documentation

Index

Constants

View Source
const TypeAny = Type("any")

TypeAny is the token used by JSON-Schema to designate that any kind of data

View Source
const TypeArray = Type("array")

TypeArray is the token used by JSON-Schema to designate that a schema describes an array.

View Source
const TypeBoolean = Type("boolean")

TypeBoolean is the token used by JSON-Schema to designate that a schema describes an boolean.

View Source
const TypeInteger = Type("integer")

TypeInteger is the token used by JSON-Schema to designate that a schema describes an integer.

View Source
const TypeNumber = Type("number")

TypeNumber is the token used by JSON-Schema to designate that a schema describes an number.

View Source
const TypeObject = Type("object")

TypeObject is the token used by JSON-Schema to designate that a schema describes an object.

View Source
const TypeString = Type("string")

TypeString is the token used by JSON-Schema to designate that a schema describes an string.

Variables

This section is empty.

Functions

func Index added in v0.10.0

func Index(token string, maxLengths ...int) (int, bool)

Index converts a string into an array index that is bounded by zero and the maximum value provided. It returns the final index and a boolean that is TRUE if the index was converted successfully, and FALSE if it was truncated.

func SetElement added in v0.10.0

func SetElement(object any, element Element, path list.List, value any) error

func UseFormat

func UseFormat(name string, fn format.Generator)

UseFormat adds a custom FormatFunc function to this library. Used to register custom validators

Types

type Any

type Any struct {
	Required   bool
	RequiredIf string
}

func (Any) Clean added in v0.10.0

func (element Any) Clean(value any) error

Clean updates a value to match the schema. The value must be a pointer.

func (Any) DefaultValue added in v0.10.0

func (element Any) DefaultValue() any

Default returns the default value for this element

func (Any) GetElement added in v0.12.0

func (element Any) GetElement(name string) (Element, bool)

func (Any) Inherit added in v0.12.0

func (element Any) Inherit(parent Element)

func (Any) IsRequired

func (element Any) IsRequired() bool

IsRequired returns true if this a value is required for this element

func (Any) MarshalMap

func (element Any) MarshalMap() map[string]any

MarshalMap populates the object data into a map[string]any

func (*Any) UnmarshalMap

func (element *Any) UnmarshalMap(data map[string]any) error

UnmarshalMap tries to populate this object using data from a map[string]any

func (Any) Validate

func (element Any) Validate(value any) error

Validate validates the provided value

func (Any) ValidateRequiredIf added in v0.13.1

func (element Any) ValidateRequiredIf(schema Schema, path list.List, globalValue any) error

ValidateRequiredIf returns an error if the conditional expression is true but the value is empty

type Array

type Array struct {
	Items      Element `json:"items"`
	MinLength  int     `json:"minLength"`
	MaxLength  int     `json:"maxLength"`
	Required   bool    `json:"required"`
	RequiredIf string  `json:"required-if"`
}

Array represents an array data type within a JSON-Schema.

func (Array) Clean added in v0.7.0

func (element Array) Clean(value any) error

func (Array) DefaultValue added in v0.6.0

func (element Array) DefaultValue() any

func (Array) GetElement added in v0.6.0

func (element Array) GetElement(name string) (Element, bool)

func (Array) GetProperty added in v0.10.0

func (element Array) GetProperty(name string) (Element, error)

func (Array) Inherit added in v0.12.0

func (element Array) Inherit(parent Element)

func (Array) IsRequired

func (element Array) IsRequired() bool

IsRequired returns TRUE if this element is a required field

func (Array) MarshalMap

func (element Array) MarshalMap() map[string]any

MarshalMap populates object data into a map[string]any

func (*Array) UnmarshalMap

func (element *Array) UnmarshalMap(data map[string]any) error

UnmarshalMap tries to populate this object using data from a map[string]any

func (Array) Validate

func (element Array) Validate(object any) error

Validate validates a value against this schema

func (Array) ValidateRequiredIf added in v0.13.1

func (element Array) ValidateRequiredIf(schema Schema, path list.List, globalValue any) error

type BoolGetter added in v0.7.0

type BoolGetter interface {
	GetBoolOK(string) (bool, bool)
}

type BoolSetter added in v0.7.0

type BoolSetter interface {
	SetBool(string, bool) bool
}

type Boolean

type Boolean struct {
	Default    null.Bool `json:"default"`
	Required   bool      `json:"required"`
	RequiredIf string    `json:"required-if"`
}

Boolean represents a boolean data type within a JSON-Schema.

func (Boolean) Clean added in v0.7.0

func (element Boolean) Clean(value any) error

func (Boolean) DefaultValue added in v0.6.0

func (element Boolean) DefaultValue() any

func (Boolean) GetElement added in v0.6.0

func (element Boolean) GetElement(name string) (Element, bool)

func (Boolean) Inherit added in v0.12.0

func (element Boolean) Inherit(parent Element)

func (Boolean) IsRequired

func (element Boolean) IsRequired() bool

IsRequired returns TRUE if this element is a required field

func (Boolean) MarshalJSON

func (element Boolean) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface

func (Boolean) MarshalMap

func (element Boolean) MarshalMap() map[string]any

MarshalMap populates object data into a map[string]any

func (*Boolean) UnmarshalMap

func (element *Boolean) UnmarshalMap(data map[string]any) error

UnmarshalMap tries to populate this object using data from a map[string]any

func (Boolean) Validate

func (element Boolean) Validate(object any) error

Validate validates a generic value using this schema

func (Boolean) ValidateRequiredIf added in v0.13.1

func (element Boolean) ValidateRequiredIf(schema Schema, path list.List, globalValue any) error

ValidateRequiredIf returns an error if the conditional expression is true but the value is empty

type Element

type Element interface {

	// Default returns the default value for this element
	DefaultValue() any

	// IsRequired returns true if this a value is required for this element
	IsRequired() bool

	// Validate validates the provided value
	Validate(value any) error

	// ValidateRequiredIf handles conditional validation of a required field
	ValidateRequiredIf(schema Schema, path list.List, globalValue any) error

	// Clean updates a value to match the schema.  The value must be a pointer.
	Clean(value any) error

	// MarshalMap populates the object data into a map[string]any
	MarshalMap() map[string]any

	// getElement returns a named sub-element of this element, if it exists.
	GetElement(string) (Element, bool)

	Inherit(Element)
}

Element interface wraps all of the methods required for schema elements.

func UnmarshalJSON

func UnmarshalJSON(data []byte) (Element, error)

UnmarshalJSON tries to parse a []byte into a schema.Element

func UnmarshalMap

func UnmarshalMap(data any) (Element, error)

UnmarshalMap tries to parse a map[string]any into a schema.Element

type ElementMap

type ElementMap map[string]Element

type Enumerator

type Enumerator interface {
	Enumerate() []string
}

type FloatGetter added in v0.7.0

type FloatGetter interface {
	GetFloatOK(string) (float64, bool)
}

type FloatSetter added in v0.7.0

type FloatSetter interface {
	SetFloat(string, float64) bool
}

type Int64Getter added in v0.7.0

type Int64Getter interface {
	GetInt64OK(string) (int64, bool)
}

type Int64Setter added in v0.7.0

type Int64Setter interface {
	SetInt64(string, int64) bool
}

type IntGetter added in v0.7.0

type IntGetter interface {
	GetIntOK(string) (int, bool)
}

type IntSetter added in v0.7.0

type IntSetter interface {
	SetInt(string, int) bool
}

type Integer

type Integer struct {
	Default    null.Int64 `json:"default"`
	Minimum    null.Int64 `json:"minimum"`
	Maximum    null.Int64 `json:"maximum"`
	MultipleOf null.Int64 `json:"multipleOf"`
	BitSize    int        `json:"bitSize"`
	Enum       []int      `json:"emum"`
	Required   bool       `json:"required"`
	RequiredIf string     `json:"required-if"`
}

Integer represents an integer data type within a JSON-Schema.

func (Integer) Clean added in v0.7.0

func (element Integer) Clean(value any) error

func (Integer) DefaultValue added in v0.6.0

func (element Integer) DefaultValue() any

DefaultValue returns the default value for this element type

func (Integer) Enumerate

func (element Integer) Enumerate() []string

Enumerate implements the "Enumerator" interface

func (Integer) GetElement added in v0.6.0

func (element Integer) GetElement(name string) (Element, bool)

func (Integer) Inherit added in v0.12.0

func (element Integer) Inherit(parent Element)

func (Integer) IsRequired

func (element Integer) IsRequired() bool

IsRequired returns TRUE if this element is a required field

func (Integer) MarshalMap

func (element Integer) MarshalMap() map[string]any

MarshalMap populates object data into a map[string]any

func (*Integer) UnmarshalMap

func (element *Integer) UnmarshalMap(data map[string]any) error

UnmarshalMap tries to populate this object using data from a map[string]any

func (Integer) Validate

func (element Integer) Validate(value any) error

Validate validates a value using this schema

func (Integer) ValidateRequiredIf added in v0.13.1

func (element Integer) ValidateRequiredIf(schema Schema, path list.List, globalValue any) error

ValidateRequiredIf returns an error if the conditional expression is true but the value is empty

type LengthGetter added in v0.10.0

type LengthGetter interface {
	Length() int
}

LengthGetter allows arrays to report their total length

type Nullable

type Nullable interface {
	IsNull() bool
}

Nullable interface wraps the IsNull method, that helps an object to identify if it contains a null value or not. This mirrors the null.Nullable interface here, for convenience.

type Number

type Number struct {
	Default    null.Float `json:"default"`
	Minimum    null.Float `json:"minimum"`
	Maximum    null.Float `json:"maximum"`
	MultipleOf null.Float `json:"multipleOf"`
	BitSize    int        `json:"bitSize"`
	Enum       []float64  `json:"enum"`
	Required   bool       `json:"required"`
	RequiredIf string     `json:"required-if"`
}

Number represents a number data type within a JSON-Schema.

func (Number) Clean added in v0.7.0

func (element Number) Clean(value any) error

func (Number) DefaultValue added in v0.6.0

func (element Number) DefaultValue() any

DefaultValue returns the default value for this element type

func (Number) Enumerate

func (element Number) Enumerate() []string

Enumerate implements the "Enumerator" interface

func (Number) GetElement added in v0.6.0

func (element Number) GetElement(name string) (Element, bool)

func (Number) Inherit added in v0.12.0

func (element Number) Inherit(parent Element)

func (Number) IsRequired

func (element Number) IsRequired() bool

IsRequired returns TRUE if this element is a required field

func (Number) MarshalMap

func (element Number) MarshalMap() map[string]any

MarshalMap populates object data into a map[string]any

func (*Number) UnmarshalMap

func (element *Number) UnmarshalMap(data map[string]any) error

UnmarshalMap tries to populate this object using data from a map[string]any

func (Number) Validate

func (element Number) Validate(value any) error

Validate validates a value against this schema

func (Number) ValidateRequiredIf added in v0.13.1

func (element Number) ValidateRequiredIf(schema Schema, path list.List, globalValue any) error

ValidateRequiredIf returns an error if the conditional expression is true but the value is empty

type Object

type Object struct {
	Properties ElementMap `json:"properties"`
	Wildcard   Element    `json:"wildcard"`
	Required   bool       `json:"required"`
	RequiredIF string     `json:"required-if"`
}

Object represents an object data type within a JSON-Schema.

func (Object) Clean added in v0.7.0

func (element Object) Clean(value any) error

func (Object) DefaultValue added in v0.6.0

func (element Object) DefaultValue() any

DefaultValue returns the default value for this element type. In a special case for objects, which can be represented as both Go structs and maps, this returns a map[string]any that has been populated with any known default keys.

func (Object) GetElement added in v0.6.0

func (element Object) GetElement(name string) (Element, bool)

func (Object) Inherit added in v0.12.0

func (element Object) Inherit(parent Element)

func (Object) IsRequired

func (element Object) IsRequired() bool

IsRequired returns TRUE if this element is a required field

func (Object) MarshalMap

func (element Object) MarshalMap() map[string]any

MarshalMap populates object data into a map[string]any

func (*Object) UnmarshalMap

func (element *Object) UnmarshalMap(data map[string]any) error

UnmarshalMap tries to populate this object using data from a map[string]any

func (Object) Validate

func (element Object) Validate(object any) error

Validate validates a value against this schema

func (Object) ValidateRequiredIf added in v0.13.1

func (element Object) ValidateRequiredIf(schema Schema, path list.List, globalValue any) error

ValidateRequiredIf returns an error if the conditional expression is true but the value is empty

type ObjectSetter added in v0.10.0

type ObjectSetter interface {
	SetObject(Element, list.List, any) error
}

type PointerGetter added in v0.14.0

type PointerGetter interface {
	GetPointer(string) (any, bool)
}

PointerGetter allows objects to return a pointer to a child object

type Remover added in v0.10.0

type Remover interface {
	Remove(string) bool
}

*****************************************

  • Remover Interface *****************************************

type Schema

type Schema struct {
	ID      string
	Comment string
	Element Element
}

Schema defines a (simplified) JSON-Schema object, that can be Marshalled/Unmarshalled to JSON.

func New

func New(element Element) Schema

New generates a fully initialized Schema object using the provided properties

func (Schema) Clean added in v0.7.0

func (schema Schema) Clean(value any) error

Clean tries to force a particular value to fit this schema by updating it (or all of its properties) to match. If values cannot be coerced to fit the schema, then an error is returned

func (Schema) Get

func (schema Schema) Get(object any, path string) (any, error)

Get retrieves a generic value from the object. If the object is nil, Get still tries to return a default value if provided by the schema

func (Schema) GetElement added in v0.6.0

func (schema Schema) GetElement(path string) (Element, bool)

func (*Schema) Inherit added in v0.12.0

func (schema *Schema) Inherit(parent Schema)

func (Schema) MarshalJSON

func (schema Schema) MarshalJSON() ([]byte, error)

MarshalJSON converts a schema into JSON.

func (Schema) MarshalMap

func (schema Schema) MarshalMap() map[string]any

MarshalMap converts a schema into a map[string]any

func (Schema) Match added in v0.13.1

func (schema Schema) Match(value any, expression exp.Expression) bool

Match returns TRUE if the provided value (as accessed via this schema) matches the provided expression. This is useful for server-side data validation.

func (Schema) Remove added in v0.6.0

func (schema Schema) Remove(object any, path string) bool

func (Schema) Set

func (schema Schema) Set(object any, path string, value any) error

func (Schema) SetAll

func (schema Schema) SetAll(object any, values map[string]any) error

SetAll iterates over Set to apply all of the values to the object one at a time, stopping at the first error it encounters. If all values are addedd successfully, then SetAll also uses Validate() to confirm that the object is still correct.

func (*Schema) UnmarshalJSON

func (schema *Schema) UnmarshalJSON(data []byte) error

UnmarshalJSON creates a new Schema object using a JSON-serialized byte array.

func (*Schema) UnmarshalMap

func (schema *Schema) UnmarshalMap(data map[string]any) error

UnmarshalMap updates a Schema using a map[string]any

func (Schema) Validate

func (schema Schema) Validate(value any) error

Validate checks a particular value against this schema. If the provided value is not valid, then an error is returned.

func (Schema) ValidateRequiredIf added in v0.13.1

func (schema Schema) ValidateRequiredIf(value any) error

type String

type String struct {
	Default    string   `json:"default"`
	MinLength  int      `json:"minLength"`
	MaxLength  int      `json:"maxLength"`
	Enum       []string `json:"enum"`
	Pattern    string   `json:"pattern"`
	Format     string   `json:"format"`
	Required   bool     `json:"required"`
	RequiredIf string   `json:"required-if"`
}

String represents a string data type within a JSON-Schema.

func (String) Clean added in v0.7.0

func (element String) Clean(value any) error

func (String) DefaultValue added in v0.6.0

func (element String) DefaultValue() any

DefaultValue returns the default value for this element type

func (String) Enumerate

func (element String) Enumerate() []string

Enumerate implements the "Enumerator" interface

func (String) GetElement added in v0.6.0

func (element String) GetElement(name string) (Element, bool)

func (String) Inherit added in v0.12.0

func (element String) Inherit(parent Element)

func (String) IsRequired

func (element String) IsRequired() bool

IsRequired returns TRUE if this element is a required field

func (String) MarshalMap

func (element String) MarshalMap() map[string]any

MarshalMap populates object data into a map[string]any

func (*String) UnmarshalMap

func (element *String) UnmarshalMap(data map[string]any) error

UnmarshalMap tries to populate this object using data from a map[string]any

func (String) Validate

func (element String) Validate(value any) error

Validate compares a generic data value using this Schema

func (String) ValidateRequiredIf added in v0.13.1

func (element String) ValidateRequiredIf(schema Schema, path list.List, globalValue any) error

ValidateRequiredIf returns an error if the conditional expression is true but the value is empty

type StringGetter added in v0.7.0

type StringGetter interface {
	GetStringOK(string) (string, bool)
}

type StringSetter added in v0.7.0

type StringSetter interface {
	SetString(string, string) bool
}

type Type

type Type string

Type enumerates all of the data types that can make up a schema

func (Type) String

func (schemaType Type) String() string

String implements the ubiquitous "Stringer" interface, so that these types can be represented as strings, if necessary

type ValueSetter added in v0.10.0

type ValueSetter interface {
	SetValue(any) error
}

type WritableElement

type WritableElement interface {

	// UnmarshalMap tries to populate this object using data from a map[string]any
	UnmarshalMap(map[string]any) error

	Element
}

WritableElement represents an Element (usually a pointer to a concrete type) whose value can be changed.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL