rest-layer: github.com/rs/rest-layer/schema Index | Examples | Files | Directories

package schema

import "github.com/rs/rest-layer/schema"

Package schema provides a validation framework for the API resources.

See http://github.com/rs/rest-layer for full REST Layer documentation.

Index

Examples

Package Files

alloff.go anyof.go array.go bool.go dependency.go dict.go doc.go field.go float.go id.go integer.go ip.go null.go object.go params.go password.go query.go reference.go schema.go string.go time.go url.go utils.go

Variables

var (
    // NewID is a field hook handler that generates a new globally unique id if none exist,
    // to be used in schema with OnInit.
    //
    // The generated ID is a Mongo like base64 object id (mgo/bson code has been embedded
    // into this function to prevent dep)
    NewID = func(ctx context.Context, value interface{}) interface{} {
        if value == nil {
            value = newID()
        }
        return value
    }

    // IDField is a common schema field configuration that generate an globally unique id
    // for new item id.
    IDField = Field{
        Description: "The item's id",
        Required:    true,
        ReadOnly:    true,
        OnInit:      NewID,
        Filterable:  true,
        Sortable:    true,
        Validator: &String{

            Regexp: "^[0-9a-v]{20}$",
        },
    }
)
var (
    // Now is a field hook handler that returns the current time, to be used in
    // schema with OnInit and OnUpdate.
    Now = func(ctx context.Context, value interface{}) interface{} {
        return time.Now()
    }
    // CreatedField is a common schema field configuration for "created" fields. It stores
    // the creation date of the item.
    CreatedField = Field{
        Description: "The time at which the item has been inserted",
        Required:    true,
        ReadOnly:    true,
        OnInit:      Now,
        Sortable:    true,
        Validator:   &Time{},
    }

    // UpdatedField is a common schema field configuration for "updated" fields. It stores
    // the current date each time the item is modified.
    UpdatedField = Field{
        Description: "The time at which the item has been last updated",
        Required:    true,
        ReadOnly:    true,
        OnInit:      Now,
        OnUpdate:    Now,
        Sortable:    true,
        Validator:   &Time{},
    }
)
var (
    // PasswordField is a common schema field for passwords. It encrypt the password using bcrypt
    // before storage and hide the value so the hash can't be read back.
    PasswordField = Field{
        Description: "Write-only field storing a secret password.",
        Required:    true,
        Hidden:      true,
        Validator:   &Password{},
    }
)
var Tombstone = internal{}

Tombstone is used to mark a field for removal

func VerifyPassword Uses

func VerifyPassword(hash interface{}, password []byte) bool

VerifyPassword compare a field of an item payload containig a hashed password with a clear text password and return true if they match.

type AllOf Uses

type AllOf []FieldValidator

AllOf validates that all the sub field validators validates

func (*AllOf) Compile Uses

func (v *AllOf) Compile() (err error)

Compile implements Compiler interface

func (AllOf) Validate Uses

func (v AllOf) Validate(value interface{}) (interface{}, error)

Validate ensures that all sub-validators validates

type And Uses

type And []Expression

And joins query clauses with a logical AND, returns all documents that match the conditions of both clauses.

func (And) Match Uses

func (e And) Match(payload map[string]interface{}) bool

Match implements Expression interface

type AnyOf Uses

type AnyOf []FieldValidator

AnyOf validates if any of the sub field validators validates

func (*AnyOf) Compile Uses

func (v *AnyOf) Compile() (err error)

Compile implements Compiler interface

func (AnyOf) Validate Uses

func (v AnyOf) Validate(value interface{}) (interface{}, error)

Validate ensures that at least one sub-validator validates

type Array Uses

type Array struct {
    // ValuesValidator is the validator to apply on array items
    ValuesValidator FieldValidator
    // MinLen defines the minimum array length (default 0)
    MinLen int
    // MaxLen defines the maximum array length (default no limit)
    MaxLen int
}

Array validates array values

func (*Array) Compile Uses

func (v *Array) Compile() (err error)

Compile implements Compiler interface

func (Array) Validate Uses

func (v Array) Validate(value interface{}) (interface{}, error)

Validate implements FieldValidator

type Bool Uses

type Bool struct {
}

Bool validates Boolean based values

func (Bool) Validate Uses

func (v Bool) Validate(value interface{}) (interface{}, error)

Validate validates and normalize Boolean based value

type Boundaries Uses

type Boundaries struct {
    Min float64
    Max float64
}

Boundaries defines min/max for an integer

type Compiler Uses

type Compiler interface {
    Compile() error
}

Compiler is an interface defining a validator that can be compiled at run time in order to check validator configuration validity and/or prepare some data for a faster execution.

type Dict Uses

type Dict struct {
    // KeysValidator is the validator to apply on dict keys
    KeysValidator FieldValidator
    // ValuesValidator is the validator to apply on dict values
    ValuesValidator FieldValidator
    // MinLen defines the minimum number of fields (default 0)
    MinLen int
    // MaxLen defines the maximum number of fields (default no limit)
    MaxLen int
}

Dict validates array values

Code:

_ = schema.Schema{
    Fields: schema.Fields{
        "dict": schema.Field{
            Validator: &schema.Dict{
                // Limit dict keys to foo and bar keys only
                KeysValidator: &schema.String{
                    Allowed: []string{"foo", "bar"},
                },
                // Allow either string or integer as dict value
                ValuesValidator: &schema.AnyOf{
                    0:  &schema.String{},
                    1:  &schema.Integer{},
                },
            },
        },
    },
}

func (*Dict) Compile Uses

func (v *Dict) Compile() (err error)

Compile implements Compiler interface

func (Dict) Validate Uses

func (v Dict) Validate(value interface{}) (interface{}, error)

Validate implements FieldValidator interface

type Equal Uses

type Equal struct {
    Field string
    Value Value
}

Equal matches all values that are equal to a specified value.

func (Equal) Match Uses

func (e Equal) Match(payload map[string]interface{}) bool

Match implements Expression interface

type ErrorMap Uses

type ErrorMap map[string][]interface{}

ErrorMap to return lots of errors

func (ErrorMap) Error Uses

func (e ErrorMap) Error() string

type Exist Uses

type Exist struct {
    Field string
}

Exist matches all values which are present, even if nil

func (Exist) Match Uses

func (e Exist) Match(payload map[string]interface{}) bool

Match implements Expression interface

type Expression Uses

type Expression interface {
    Match(payload map[string]interface{}) bool
}

Expression is a query or query component that can be matched against a payoad.

type Field Uses

type Field struct {
    // Description stores a short description of the field useful for automatic
    // documentation generation.
    Description string
    // Required throws an error when the field is not provided at creation.
    Required bool
    // ReadOnly throws an error when a field is changed by the client.
    // Default and OnInit/OnUpdate hooks can be used to set/change read-only
    // fields.
    ReadOnly bool
    // Hidden allows writes but hides the field's content from the client. When
    // this field is enabled, PUTing the document without the field would not
    // remove the field but use the previous document's value if any.
    Hidden bool
    // Default defines the value be stored on the field when when item is
    // created and this field is not provided by the client.
    Default interface{}
    // OnInit can be set to a function to generate the value of this field
    // when item is created. The function takes the current value if any
    // and returns the value to be stored.
    OnInit func(ctx context.Context, value interface{}) interface{}
    // OnUpdate can be set to a function to generate the value of this field
    // when item is updated. The function takes the current value if any
    // and returns the value to be stored.
    OnUpdate func(ctx context.Context, value interface{}) interface{}
    // Params defines a param handler for the field. The handler may change the field's
    // value depending on the passed parameters.
    Params Params
    // Handler is the piece of logic modifying the field value based on passed parameters.
    // This handler is only called if at least on parameter is provided.
    Handler FieldHandler
    // Validator is used to validate the field's format. Please note you *must* pass in pointers to
    // FieldValidator instances otherwise `schema` will not be able to discover other interfaces,
    // such as `Compiler`, and *will* prevent schema from initializing specific FieldValidators
    // correctly causing unexpected runtime errors.
    // @see http://research.swtch.com/interfaces for more details.
    Validator FieldValidator
    // Dependency rejects the field if the schema query doesn't match the document.
    // Use schema.Q(`{"field": "value"}`) to populate this field.
    Dependency *PreQuery
    // Filterable defines that the field can be used with the `filter` parameter.
    // When this property is set to `true`, you may want to ensure the backend
    // database has this field indexed.
    Filterable bool
    // Sortable defines that the field can be used with the `sort` parameter.
    // When this property is set to `true`, you may want to ensure the backend
    // database has this field indexed.
    Sortable bool
    // Schema can be set to a sub-schema to allow multi-level schema.
    Schema *Schema
}

Field specifies the info for a single field of a spec

func (Field) Compile Uses

func (f Field) Compile() error

Compile implements Compiler interface and recusively compile sub schemas and validators when they implement Compiler interface

type FieldHandler Uses

type FieldHandler func(ctx context.Context, value interface{}, params map[string]interface{}) (interface{}, error)

FieldHandler is the piece of logic modifying the field value based on passed parameters

type FieldSerializer Uses

type FieldSerializer interface {
    // Serialize is called when the data is coming from it internal storable form and
    // needs to be prepared for representation (i.e.: just before JSON marshaling)
    Serialize(value interface{}) (interface{}, error)
}

FieldSerializer is used to convert the value between it's representation form and it internal storable form. A FieldValidator which implement this interface will have its Serialize method called before marshaling.

type FieldValidator Uses

type FieldValidator interface {
    Validate(value interface{}) (interface{}, error)
}

FieldValidator is an interface for all individual validators. It takes a value to validate as argument and returned the normalized value or an error if validation failed.

type Fields Uses

type Fields map[string]Field

Fields defines a map of name -> field pairs

type Float Uses

type Float struct {
    Allowed    []float64
    Boundaries *Boundaries
}

Float validates float based values

func (Float) Validate Uses

func (v Float) Validate(value interface{}) (interface{}, error)

Validate validates and normalize float based value

type GreaterOrEqual Uses

type GreaterOrEqual struct {
    Field string
    Value float64
}

GreaterOrEqual matches values that are greater than or equal to a specified value.

func (GreaterOrEqual) Match Uses

func (e GreaterOrEqual) Match(payload map[string]interface{}) bool

Match implements Expression interface

type GreaterThan Uses

type GreaterThan struct {
    Field string
    Value float64
}

GreaterThan matches values that are greater than a specified value.

func (GreaterThan) Match Uses

func (e GreaterThan) Match(payload map[string]interface{}) bool

Match implements Expression interface

type IP Uses

type IP struct {
    // StoreBinary activates storage of the IP as binary to save space.
    // The storage requirement is 4 bytes for IPv4 and 16 bytes for IPv6.
    StoreBinary bool
}

IP validates IP values

func (IP) Serialize Uses

func (v IP) Serialize(value interface{}) (interface{}, error)

Serialize implements FieldSerializer

func (IP) Validate Uses

func (v IP) Validate(value interface{}) (interface{}, error)

Validate implements FieldValidator

type In Uses

type In struct {
    Field  string
    Values []Value
}

In natches any of the values specified in an array.

func (In) Match Uses

func (e In) Match(payload map[string]interface{}) bool

Match implements Expression interface

type Integer Uses

type Integer struct {
    Allowed    []int
    Boundaries *Boundaries
}

Integer validates integer based values

func (Integer) Validate Uses

func (v Integer) Validate(value interface{}) (interface{}, error)

Validate validates and normalize integer based value

type LowerOrEqual Uses

type LowerOrEqual struct {
    Field string
    Value float64
}

LowerOrEqual matches values that are less than or equal to a specified value.

func (LowerOrEqual) Match Uses

func (e LowerOrEqual) Match(payload map[string]interface{}) bool

Match implements Expression interface

type LowerThan Uses

type LowerThan struct {
    Field string
    Value float64
}

LowerThan matches values that are less than a specified value.

func (LowerThan) Match Uses

func (e LowerThan) Match(payload map[string]interface{}) bool

Match implements Expression interface

type NotEqual Uses

type NotEqual struct {
    Field string
    Value Value
}

NotEqual matches all values that are not equal to a specified value.

func (NotEqual) Match Uses

func (e NotEqual) Match(payload map[string]interface{}) bool

Match implements Expression interface

type NotExist Uses

type NotExist struct {
    Field string
}

NotExist matches all values which are absent

func (NotExist) Match Uses

func (e NotExist) Match(payload map[string]interface{}) bool

Match implements Expression interface

type NotIn Uses

type NotIn struct {
    Field  string
    Values []Value
}

NotIn matches none of the values specified in an array.

func (NotIn) Match Uses

func (e NotIn) Match(payload map[string]interface{}) bool

Match implements Expression interface

type Null Uses

type Null []FieldValidator

Null validates that the value is null.

func (Null) Validate Uses

func (v Null) Validate(value interface{}) (interface{}, error)

Validate ensures that value is null

type Object Uses

type Object struct {
    Schema *Schema
}

Object validates objects which are defined by Schemas.

func (*Object) Compile Uses

func (v *Object) Compile() error

Compile implements Compiler interface

func (Object) Validate Uses

func (v Object) Validate(value interface{}) (interface{}, error)

Validate implements FieldValidator interface

type Or Uses

type Or []Expression

Or joins query clauses with a logical OR, returns all documents that match the conditions of either clause.

func (Or) Match Uses

func (e Or) Match(payload map[string]interface{}) bool

Match implements Expression interface

type Param Uses

type Param struct {
    // Description of the parameter
    Description string
    // Validator to use for this parameter
    Validator FieldValidator
}

Param define an individual field parameter with its validator

type Params Uses

type Params map[string]Param

Params defines param name => definition pairs allowed for a field

type Password Uses

type Password struct {
    // MinLen defines the minimum password length (default 0)
    MinLen int
    // MaxLen defines the maximum password length (default no limit)
    MaxLen int
    // Cost sets a custom bcrypt hashing cose.
    Cost int
}

Password cryptes a field password using bcrypt algorithm

func (Password) Validate Uses

func (v Password) Validate(value interface{}) (interface{}, error)

Validate implements FieldValidator interface

type PreQuery Uses

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

PreQuery stores a query as string so it can be parsed/validated later

func Q Uses

func Q(q string) *PreQuery

Q is like ParseQuery, but returns an intermediate object which can be stored before behing parsed.

type Query Uses

type Query []Expression

Query defines an expression against a schema to perform a match on schema's data.

func NewQuery Uses

func NewQuery(q map[string]interface{}, validator Validator) (Query, error)

NewQuery returns a new query with the provided key/value validated against validator

func ParseQuery Uses

func ParseQuery(query string, validator Validator) (Query, error)

ParseQuery parses and validate a query as string

func (Query) Match Uses

func (e Query) Match(payload map[string]interface{}) bool

Match implements Expression interface

type Reference Uses

type Reference struct {
    Path string
}

Reference validates time based values

func (Reference) Validate Uses

func (v Reference) Validate(value interface{}) (interface{}, error)

Validate validates and normalize reference based value

type Regex Uses

type Regex struct {
    Field string
    Value *regexp.Regexp
}

Regex matches values that match to a specified regular expression.

func (Regex) Match Uses

func (e Regex) Match(payload map[string]interface{}) bool

Match implements Expression interface

type Schema Uses

type Schema struct {
    // Description of the object described by this schema
    Description string
    // Fields defines the schema's allowed fields
    Fields Fields
    // MinLen defines the minimum number of fields (default 0)
    MinLen int
    // MaxLen defines the maximum number of fields (default no limit)
    MaxLen int
}

Schema defines fields for a document

func (Schema) Compile Uses

func (s Schema) Compile() error

Compile implements Compiler interface and call the same function on each field. Note: if you use schema as a standalone library, it is the *caller's* responsibility to invoke the Compile method before using Prepare or Validate on a Schema instance, otherwise FieldValidator instances may not be initialized correctly.

func (Schema) GetField Uses

func (s Schema) GetField(name string) *Field

GetField returns the validator for the field if the given field name is present in the schema.

You may reference sub field using dotted notation field.subfield

func (Schema) Prepare Uses

func (s Schema) Prepare(ctx context.Context, payload map[string]interface{}, original *map[string]interface{}, replace bool) (changes map[string]interface{}, base map[string]interface{})

Prepare takes a payload with an optional original payout when updating an existing item and return two maps, one containing changes operated by the user and another defining either exising data (from the current item) or data generated by the system thru "default" value or hooks.

If the original map is nil, prepare will act as if the payload is a new document. The OnInit hook is executed for each field if any, and default values are assigned to missing fields.

When the original map is defined, the payload is considered as an update on the original document, default values are not assigned, and only fields which are different than in the original are left in the change map. The OnUpdate hook is executed on each field.

If the replace argument is set to true with the original document set, the behavior is slightly different as any field not present in the payload but present in the original are set to nil in the change map (instead of just behing absent). This instruct the validator that the field has been edited, so ReadOnly flag can throw an error and the field will be removed from the output document. The OnInit is also called instead of the OnUpdate.

func (Schema) Validate Uses

func (s Schema) Validate(changes map[string]interface{}, base map[string]interface{}) (doc map[string]interface{}, errs map[string][]interface{})

Validate validates changes applied on a base document in regard to the schema and generate an result document with the changes applied to the base document. All errors in the process are reported in the returned errs value.

type String Uses

type String struct {
    Regexp  string
    Allowed []string
    MaxLen  int
    MinLen  int
    // contains filtered or unexported fields
}

String validates string based values

func (*String) Compile Uses

func (v *String) Compile() (err error)

Compile compiles and validate regexp if any

func (String) Validate Uses

func (v String) Validate(value interface{}) (interface{}, error)

Validate validates and normalize string based value

type Time Uses

type Time struct {
    TimeLayouts []string // TimeLayouts is set of time layouts we want to validate
    // contains filtered or unexported fields
}

Time validates time based values

func (*Time) Compile Uses

func (v *Time) Compile() (err error)

Compile the time formats

func (Time) Validate Uses

func (v Time) Validate(value interface{}) (interface{}, error)

Validate validates and normalize time based value

type URL Uses

type URL struct {
    AllowRelative  bool
    AllowLocale    bool
    AllowNonHTTP   bool
    AllowedSchemes []string
}

URL validates URLs values

func (URL) Validate Uses

func (v URL) Validate(value interface{}) (interface{}, error)

Validate validates URL values

type Validator Uses

type Validator interface {
    GetField(name string) *Field
    Prepare(ctx context.Context, payload map[string]interface{}, original *map[string]interface{}, replace bool) (changes map[string]interface{}, base map[string]interface{})
    Validate(changes map[string]interface{}, base map[string]interface{}) (doc map[string]interface{}, errs map[string][]interface{})
}

Validator is an interface used to validate schema against actual data

type Value Uses

type Value interface{}

Value represents any kind of value to use in query

Directories

PathSynopsis
encodingPackage encoding is the intended hierarchy location for encoding Schema to other formats.
encoding/jsonschemaPackage jsonschema provides JSON Schema Draft 4 encoding support for schema.Schema.

Package schema imports 15 packages (graph) and is imported by 10 packages. Updated 2017-03-09. Refresh now. Tools for package owners.