schema

package module
v0.15.1 Latest Latest
Warning

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

Go to latest
Published: Jun 10, 2022 License: Apache-2.0 Imports: 11 Imported by: 2

README

schema 👍

GoDoc Build Status 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
What's Left Out
  • References
  • Loading remote Schemas by URI.

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

Examples

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.

View Source
const ValidationErrorCode = 422

ValidationErrorCode represents HTTP Status Code: 422 "Unproccessable Entity"

Variables

This section is empty.

Functions

func UseFormat added in v0.8.1

func UseFormat(name string, fn format.Function)

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

Types

type Any added in v0.4.0

type Any struct {
	Required bool
}

Any represents a any data type within a JSON-Schema.

func (Any) Get added in v0.15.0

func (element Any) Get(object reflect.Value, path string) (any, Element, error)

Find locates a child of this element

func (Any) IsRequired added in v0.15.1

func (element Any) IsRequired() bool

IsRequired returns TRUE if this element is a required field

func (Any) MarshalMap added in v0.5.0

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

MarshalMap populates object data into a map[string]any

func (Any) Set added in v0.15.0

func (element Any) Set(object reflect.Value, path string, value any) error

Set formats a value and applies it to the provided object/path

func (Any) Type added in v0.4.0

func (element Any) Type() reflect.Type

Type returns the data type of this Element

func (*Any) UnmarshalMap added in v0.5.0

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 added in v0.4.0

func (element Any) Validate(value any) error

Validate validates a value against this schema

type Array

type Array struct {
	Items     Element
	MinLength null.Int
	MaxLength null.Int
	Required  bool
}

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

func (Array) Get added in v0.15.0

func (element Array) Get(object reflect.Value, path string) (any, Element, error)

Find locates a child of this element

func (Array) IsRequired added in v0.15.1

func (element Array) IsRequired() bool

IsRequired returns TRUE if this element is a required field

func (Array) MarshalMap added in v0.5.0

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

MarshalMap populates object data into a map[string]any

func (Array) Set added in v0.15.0

func (element Array) Set(object reflect.Value, path string, value any) error

Set formats/validates a generic value using this schema

func (Array) Type

func (element Array) Type() reflect.Type

Type returns the reflection type of this Element

func (*Array) UnmarshalMap added in v0.3.0

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(value any) error

Validate validates a value against this schema

type Boolean

type Boolean struct {
	Default  null.Bool `json:"default"`
	Required bool
}

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

func (Boolean) Get added in v0.15.0

func (element Boolean) Get(object reflect.Value, path string) (any, Element, error)

Find locates a child of this element

func (Boolean) IsRequired added in v0.15.1

func (element Boolean) IsRequired() bool

IsRequired returns TRUE if this element is a required field

func (Boolean) MarshalJSON added in v0.9.1

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

MarshalJSON implements the json.Marshaler interface

func (Boolean) MarshalMap added in v0.5.0

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

MarshalMap populates object data into a map[string]any

func (Boolean) Set added in v0.15.0

func (element Boolean) Set(object reflect.Value, path string, value any) error

Set formats a value and applies it to the provided object/path

func (Boolean) Type

func (element Boolean) Type() reflect.Type

Type returns the data type of this Element

func (*Boolean) UnmarshalMap added in v0.5.0

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

type Element added in v0.5.0

type Element interface {

	// Type returns the Type of this particular schema element
	Type() reflect.Type

	// Find uses the path to locate a value in an object along with the schema that defines it.
	Get(object reflect.Value, path string) (any, Element, error)

	// Set formats a value and applies it to the provided object/path
	Set(object reflect.Value, path string, value any) error

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

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

	IsRequired() bool
}

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

func UnmarshalJSON added in v0.5.0

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

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

func UnmarshalMap added in v0.5.0

func UnmarshalMap(data any) (Element, error)

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

type ElementMap added in v0.15.0

type ElementMap map[string]Element

type Enumerator added in v0.10.1

type Enumerator interface {
	Enumerate() []string
}

type Integer

type Integer struct {
	Default    null.Int64 `json:"default"` // TODO: Int64??
	Minimum    null.Int64 `json:"minimum"`
	Maximum    null.Int64 `json:"maximum"`
	MultipleOf null.Int64 `json:"multipleOf"`
	Enum       []int      `json:"emum"`
	Required   bool
}

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

func (Integer) Enumerate added in v0.10.1

func (element Integer) Enumerate() []string

Enumerate implements the "Enumerator" interface

func (Integer) Get added in v0.15.0

func (element Integer) Get(object reflect.Value, path string) (any, Element, error)

Find locates a child of this element

func (Integer) IsRequired added in v0.15.1

func (element Integer) IsRequired() bool

IsRequired returns TRUE if this element is a required field

func (Integer) MarshalMap added in v0.5.0

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

MarshalMap populates object data into a map[string]any

func (Integer) Set added in v0.15.0

func (element Integer) Set(object reflect.Value, path string, value any) error

Set formats a value and applies it to the provided object/path

func (Integer) Type

func (element Integer) Type() reflect.Type

Type returns the data type of this Schema

func (*Integer) UnmarshalMap added in v0.5.0

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

type Nullable added in v0.9.0

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"`
	Enum       []float64  `json:"enum"`
	Required   bool
}

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

func (Number) Enumerate added in v0.10.1

func (element Number) Enumerate() []string

Enumerate implements the "Enumerator" interface

func (Number) Get added in v0.15.0

func (element Number) Get(object reflect.Value, path string) (any, Element, error)

Find locates a child of this element

func (Number) IsRequired added in v0.15.1

func (element Number) IsRequired() bool

IsRequired returns TRUE if this element is a required field

func (Number) MarshalMap added in v0.5.0

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

MarshalMap populates object data into a map[string]any

func (Number) Set added in v0.15.0

func (element Number) Set(object reflect.Value, path string, value any) error

Set formats a value and applies it to the provided object/path

func (Number) Type

func (element Number) Type() reflect.Type

Type returns the data type of this Element

func (*Number) UnmarshalMap added in v0.5.0

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

type Object

type Object struct {
	Properties    ElementMap
	RequiredProps []string
	Required      bool
}

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

func (Object) Get added in v0.15.0

func (element Object) Get(object reflect.Value, path string) (any, Element, error)

Find locates a child of this element

func (Object) IsRequired added in v0.15.1

func (element Object) IsRequired() bool

IsRequired returns TRUE if this element is a required field

func (Object) MarshalMap added in v0.5.0

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

MarshalMap populates object data into a map[string]any

func (Object) Set added in v0.15.0

func (element Object) Set(object reflect.Value, path string, value any) error

Set validates/formats a value using this schema

func (Object) Type

func (element Object) Type() reflect.Type

Type returns the data type of this Element

func (*Object) UnmarshalMap added in v0.5.0

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(value any) error

Validate validates a value against this schema

type PathGetter added in v0.15.0

type PathGetter interface {
	GetPath(path string) (any, error)
}

type PathSetter added in v0.15.0

type PathSetter interface {
	SetPath(path string, value any) error
}

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(properties ElementMap) Schema

New generates a fully initialized Schema object using the provided properties

func Unmarshal added in v0.9.2

func Unmarshal(original string) Schema

Unmarshal converts a JSON string into a schema. If the string cannot be converted, then an empty schema is returned.

func (Schema) Get added in v0.15.0

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

Get retrieves a generic value from the object, along with the schema element that defines it. If the object is nil, Get still tries to return a default value if provided by the schema

func (Schema) GetBool added in v0.15.0

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

GetBool retrieves a bool value from this object. If the value is not defined in the object/schema, then the zero value (false) is returned

func (Schema) GetFloat added in v0.15.0

func (schema Schema) GetFloat(object any, path string) float64

GetFloat retrieves a float64 value from this object. If the value is not defined in the object/schema, then the zero value (0.0) is returned

func (Schema) GetInt added in v0.15.0

func (schema Schema) GetInt(object any, path string) int

GetInt retrieves a int value from this object. If the value is not defined in the object/schema, then the zero value (0) is returned

func (Schema) GetInt64 added in v0.15.0

func (schema Schema) GetInt64(object any, path string) int64

GetInt64 retrieves an int64 value from this object. If the value is not defined in the object/schema, then the zero value (0) is returned

func (Schema) GetString added in v0.15.0

func (schema Schema) GetString(object any, path string) string

GetString retrieves a string value from this object. If the value is not defined in the object/schema, then the zero value ("") is returned

func (Schema) MarshalJSON added in v0.6.1

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

MarshalJSON converts a schema into JSON.

func (Schema) MarshalMap added in v0.6.1

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

MarshalMap converts a schema into a map[string]any

func (Schema) Set added in v0.11.0

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

Schema applies a value to the object at the given path. If the path is invalid then it returns an error

func (Schema) SetAll added in v0.15.0

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 added in v0.5.0

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

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

func (*Schema) UnmarshalMap added in v0.6.1

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.

type String

type String struct {
	Default   string
	MinLength null.Int
	MaxLength null.Int
	Enum      []string
	Pattern   string
	Format    string
	Required  bool
}

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

func (String) Enumerate added in v0.10.1

func (element String) Enumerate() []string

Enumerate implements the "Enumerator" interface

func (String) Get added in v0.15.0

func (element String) Get(object reflect.Value, path string) (any, Element, error)

Find locates a child of this element

func (String) IsRequired added in v0.15.1

func (element String) IsRequired() bool

IsRequired returns TRUE if this element is a required field

func (String) MarshalMap added in v0.5.0

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

MarshalMap populates object data into a map[string]any

func (String) Set added in v0.15.0

func (element String) Set(object reflect.Value, path string, value any) error

Set validates/formats a generic value using this schema

func (String) Type

func (element String) Type() reflect.Type

Type returns the data type of this Element

func (*String) UnmarshalMap added in v0.5.0

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

type Type added in v0.3.0

type Type string

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

func (Type) String added in v0.3.0

func (schemaType Type) String() string

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

type ValidationError added in v0.8.1

type ValidationError struct {
	Path    string `json:"path"`    // Identifies the PATH (or variable name) that has invalid input
	Message string `json:"message"` // Human-readable message that explains the problem with the input value.
}

ValidationError represents an input validation error, and includes fields necessary to report problems back to the end user.

Example
// Derp includes a custom error type for data validation, that tracks
// the name (or path) of the invalid field and the reason that it is invalid

err := Invalid("Field is required, or is too short, or is something else we don't like.")

// ValidationErrors work anywhere that a standard error works
fmt.Println(err.Error())

// Derp can also calculates the HTTP error code for ValidationErrors, which is 422 "Unprocessable Entity".
fmt.Println(derp.ErrorCode(err))
Output:

Field is required, or is too short, or is something else we don't like.
422

func Invalid added in v0.8.1

func Invalid(message string) ValidationError

Invalid returns a fully populated ValidationError to the caller

func (ValidationError) Error added in v0.8.1

func (v ValidationError) Error() string

Error returns a string representation of this ValidationError, and implements the builtin errors.error interface.

func (ValidationError) ErrorCode added in v0.8.1

func (v ValidationError) ErrorCode() int

ErrorCode returns CodeValidationError for this ValidationError It implements the ErrorCodeGetter interface.

type WritableElement added in v0.6.0

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