schematypes

package module
v0.0.0-...-d255d06 Latest Latest
Warning

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

Go to latest
Published: Oct 14, 2019 License: MPL-2.0 Imports: 11 Imported by: 30

README

Package schematypes

Build Status

Package schematypes provides types for constructing JSON schemas programmatically. This is useful when having a plugin architecture that accepts JSON matching a given schema as input. As this will allow nesting of plugins.

Example using an integer, works the same for objects and arrays.


import (
  "encoding/json"
  "fmt"

  "github.com/taskcluster/go-schematypes"
)

func main() {
  // Define a schema
  schema := schematypes.Integer{
    MetaData: schematypes.MetaData{
      Title:       "my-title",
      Description: "my-description",
    },
    Minimum: -240,
    Maximum: 240,
  }

  // Parse JSON
  var data interface{}
  err := json.Unmarshal(data, []byte(`234`))
  if err != nil {
    panic("JSON parsing error")
  }

  // Validate against schema
  err = schema.Validate(data)
  if err != nil {
    panic("JSON didn't validate against schema")
  }

  // Map parse data without casting, this is particularly useful for JSON
  // structures as they can be mapped to structs with the `json:"..."` tag.
  var result int
  err = schema.Map(&result, data)
  if err != nil {
    panic("JSON validation failed, or type given to map doesn't match the schema")
  }

  // Now we can use the value we mapped out
  fmt.Println(result)
}

License

This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

Documentation

Overview

Package schematypes provides types for constructing JSON schemas programmatically. This is useful when having a plugin architecture that accepts JSON matching a given schema as input. As this will allow nesting of plugins.

Index

Constants

This section is empty.

Variables

View Source
var ErrTypeMismatch = errors.New("Type does not match the schema")

ErrTypeMismatch is returned when trying to map to a type that doesn't match or which isn't writable (for example passed by value and not pointer).

Functions

func MustMap

func MustMap(schema Schema, data, target interface{}) error

MustMap will map data into target using schema and panic, if it returns ErrTypeMismatch

func MustValidate

func MustValidate(schema Schema, data interface{})

MustValidate panics if data doesn't validate against schema

func MustValidateAndMap

func MustValidateAndMap(schema Schema, data, target interface{})

MustValidateAndMap panics if data doesn't validate or maps into target

Types

type AllOf

type AllOf []Schema

An AllOf instance represents the allOf JSON schema construction.

func (AllOf) Map

func (s AllOf) Map(data, target interface{}) error

Map takes data, validates and maps it into the target reference.

func (AllOf) Schema

func (s AllOf) Schema() map[string]interface{}

Schema returns a JSON representation of the schema.

func (AllOf) Validate

func (s AllOf) Validate(data interface{}) error

Validate the given data, this will return nil if data satisfies this schema. Otherwise, Validate(data) returns a ValidationError instance.

type AnyOf

type AnyOf []Schema

An AnyOf instance represents the anyOf JSON schema construction.

func (AnyOf) Map

func (s AnyOf) Map(data, target interface{}) error

Map takes data, validates and maps it into the target reference.

func (AnyOf) Schema

func (s AnyOf) Schema() map[string]interface{}

Schema returns a JSON representation of the schema.

func (AnyOf) Validate

func (s AnyOf) Validate(data interface{}) error

Validate the given data, this will return nil if data satisfies this schema. Otherwise, Validate(data) returns a ValidationError instance.

type Array

type Array struct {
	Title       string
	Description string
	Items       Schema
	Unique      bool
}

An Array struct represents the JSON schema for an array.

func (Array) Map

func (a Array) Map(data, target interface{}) error

Map takes data, validates and maps it into the target reference.

func (Array) Schema

func (a Array) Schema() map[string]interface{}

Schema returns a JSON representation of the schema.

func (Array) Validate

func (a Array) Validate(data interface{}) error

Validate the given data, this will return nil if data satisfies this schema. Otherwise, Validate(data) returns a ValidationError instance.

type Boolean

type Boolean struct {
	Title       string
	Description string
}

Boolean schema type.

func (Boolean) Map

func (b Boolean) Map(data interface{}, target interface{}) error

Map takes data, validates and maps it into the target reference.

func (Boolean) Schema

func (b Boolean) Schema() map[string]interface{}

Schema returns a JSON representation of the schema.

func (Boolean) Validate

func (b Boolean) Validate(data interface{}) error

Validate the given data, this will return nil if data satisfies this schema. Otherwise, Validate(data) returns a ValidationError instance.

type DateTime

type DateTime struct {
	Title       string
	Description string
}

DateTime schema type for strings with format: date-time.

func (DateTime) Map

func (d DateTime) Map(data interface{}, target interface{}) error

Map takes data, validates and maps it into the target reference.

func (DateTime) Schema

func (d DateTime) Schema() map[string]interface{}

Schema returns a JSON representation of the schema.

func (DateTime) Validate

func (d DateTime) Validate(data interface{}) error

Validate the given data, this will return nil if data satisfies this schema. Otherwise, Validate(data) returns a ValidationError instance.

type Duration

type Duration struct {
	Title         string
	Description   string
	AllowNegative bool
}

Duration schema type for duration as integer seconds or string on the form:

/[-+]? (\d+ d(ays?)?)? (\d+ h((ours?)?|r))? (\d+ m(in(untes?)?)?)?/

This allows for a lot of human readable time durations, examples:

'31 days 2 hours 5 min'
'5 min'
'2 hours 5 min'
'+ 3 minutes'
'- 2 hr'
'- 3 days'
'1d2h3m'
'   1  day  2 hour  1 minutes '

func (Duration) Map

func (d Duration) Map(data interface{}, target interface{}) error

Map takes data, validates and maps it into the target reference.

func (Duration) Schema

func (d Duration) Schema() map[string]interface{}

Schema returns a JSON representation of the schema.

func (Duration) Validate

func (d Duration) Validate(data interface{}) error

Validate the given data, this will return nil if data satisfies this schema. Otherwise, Validate(data) returns a ValidationError instance.

type Integer

type Integer struct {
	Title       string
	Description string
	Minimum     int64
	Maximum     int64
}

The Integer struct represents a JSON schema for an integer.

func (Integer) Map

func (i Integer) Map(data interface{}, target interface{}) error

Map takes data, validates and maps it into the target reference.

func (Integer) Schema

func (i Integer) Schema() map[string]interface{}

Schema returns a JSON representation of the schema.

func (Integer) Validate

func (i Integer) Validate(data interface{}) error

Validate the given data, this will return nil if data satisfies this schema. Otherwise, Validate(data) returns a ValidationError instance.

type IntegerEnum

type IntegerEnum struct {
	Title       string
	Description string
	Options     []int
}

IntegerEnum schema type for enums of integers.

func (IntegerEnum) Map

func (s IntegerEnum) Map(data interface{}, target interface{}) error

Map takes data, validates and maps it into the target reference.

func (IntegerEnum) Schema

func (s IntegerEnum) Schema() map[string]interface{}

Schema returns a JSON representation of the schema.

func (IntegerEnum) Validate

func (s IntegerEnum) Validate(data interface{}) error

Validate the given data, this will return nil if data satisfies this schema. Otherwise, Validate(data) returns a ValidationError instance.

type Map

type Map struct {
	Title             string
	Description       string
	Values            Schema
	MinimumProperties int64
	MaximumProperties int64
}

Map specifies schema for a map from string to values.

func (Map) Map

func (m Map) Map(data, target interface{}) error

Map takes data, validates and maps it into the target reference.

func (Map) Schema

func (m Map) Schema() map[string]interface{}

Schema returns a JSON representation of the schema.

func (Map) Validate

func (m Map) Validate(data interface{}) error

Validate the given data, this will return nil if data satisfies this schema. Otherwise, Validate(data) returns a ValidationError instance.

type Number

type Number struct {
	Title       string
	Description string
	Minimum     float64
	Maximum     float64
}

Number schema type.

func (Number) Map

func (n Number) Map(data interface{}, target interface{}) error

Map takes data, validates and maps it into the target reference.

func (Number) Schema

func (n Number) Schema() map[string]interface{}

Schema returns a JSON representation of the schema.

func (Number) Validate

func (n Number) Validate(data interface{}) error

Validate the given data, this will return nil if data satisfies this schema. Otherwise, Validate(data) returns a ValidationError instance.

type Object

type Object struct {
	Title                string
	Description          string
	Properties           Properties
	AdditionalProperties bool
	Required             []string
}

Object specifies schema for an object.

func Merge

func Merge(a ...Object) (Object, error)

Merge multiple object schemas, this will create an object schema with all the properties from the schemas given, and all the required properties as the given object schemas have.

This will fail if any schema has AdditionalProperties: true, or if any two schemas specifies the same key with different schemas.

When using this to merge multiple schemas into one schema, the Object.Filter method may be useful to strip forbidden properties such that the subset of values matching a specific schema used can be extract for use with Object.Validate or Object.Map.

func (Object) Filter

func (o Object) Filter(data map[string]interface{}) map[string]interface{}

Filter will create a new map with any additional properties that aren't allowed by the schema removed. This doesn't modify the data parameter, but returns a new map.

Note: Naturally this have no effect if AdditionalProperties is true.

func (Object) Map

func (o Object) Map(data, target interface{}) error

Map takes data, validates and maps it into the target reference.

func (Object) Schema

func (o Object) Schema() map[string]interface{}

Schema returns a JSON representation of the schema.

func (Object) Validate

func (o Object) Validate(data interface{}) error

Validate the given data, this will return nil if data satisfies this schema. Otherwise, Validate(data) returns a ValidationError instance.

type OneOf

type OneOf []Schema

A OneOf instance represents the oneOf JSON schema construction.

func (OneOf) Map

func (s OneOf) Map(data, target interface{}) error

Map takes data, validates and maps it into the target reference.

func (OneOf) Schema

func (s OneOf) Schema() map[string]interface{}

Schema returns a JSON representation of the schema.

func (OneOf) Validate

func (s OneOf) Validate(data interface{}) error

Validate the given data, this will return nil if data satisfies this schema. Otherwise, Validate(data) returns a ValidationError instance.

type Properties

type Properties map[string]Schema

Properties defines the properties for a object schema.

type Schema

type Schema interface {
	Schema() map[string]interface{}
	Validate(data interface{}) error
	Map(data, target interface{}) error
}

A Schema is implemented by any object that can represent a JSON schema.

func NewSchema

func NewSchema(jsonschema interface{}) (Schema, error)

NewSchema creates a Schema that wraps a jsonschema. The jsonschema can be specified as a JSON string or a hierarchy of

  • map[string]interface{}
  • []interface{}
  • string
  • float64
  • bool
  • nil

type String

type String struct {
	Title         string
	Description   string
	MinimumLength int
	MaximumLength int
	Pattern       string
}

String schema type.

func (String) Map

func (s String) Map(data interface{}, target interface{}) error

Map takes data, validates and maps it into the target reference.

func (String) Schema

func (s String) Schema() map[string]interface{}

Schema returns a JSON representation of the schema.

func (String) Validate

func (s String) Validate(data interface{}) error

Validate the given data, this will return nil if data satisfies this schema. Otherwise, Validate(data) returns a ValidationError instance.

type StringEnum

type StringEnum struct {
	Title       string
	Description string
	Options     []string
}

StringEnum schema type for enums of strings.

func (StringEnum) Map

func (s StringEnum) Map(data interface{}, target interface{}) error

Map takes data, validates and maps it into the target reference.

func (StringEnum) Schema

func (s StringEnum) Schema() map[string]interface{}

Schema returns a JSON representation of the schema.

func (StringEnum) Validate

func (s StringEnum) Validate(data interface{}) error

Validate the given data, this will return nil if data satisfies this schema. Otherwise, Validate(data) returns a ValidationError instance.

type URI

type URI struct {
	Title       string
	Description string
	Options     []string
}

URI schema type for strings with format: uri.

func (URI) Map

func (s URI) Map(data interface{}, target interface{}) error

Map takes data, validates and maps it into the target reference.

func (URI) Schema

func (s URI) Schema() map[string]interface{}

Schema returns a JSON representation of the schema.

func (URI) Validate

func (s URI) Validate(data interface{}) error

Validate the given data, this will return nil if data satisfies this schema. Otherwise, Validate(data) returns a ValidationError instance.

type ValidationError

type ValidationError struct {
	// contains filtered or unexported fields
}

ValidationError represents a validation failure as a list of validation issues.

func (*ValidationError) Error

func (e *ValidationError) Error() string

func (*ValidationError) Issues

func (e *ValidationError) Issues(rootName string) []ValidationIssue

Issues returns the validation issues with given rootName as the start of the Path or "root" if rootName is the empty string.

type ValidationIssue

type ValidationIssue struct {
	// contains filtered or unexported fields
}

A ValidationIssue is any error found validating a JSON object.

func (*ValidationIssue) Path

func (v *ValidationIssue) Path() string

Path returns the a path to the issue, on the form:

rootName.dictionary["other-key"].array[44].property

func (*ValidationIssue) String

func (v *ValidationIssue) String() string

String returns a human readable string representation of the issue

Jump to

Keyboard shortcuts

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