Movatterモバイル変換


[0]ホーム

URL:


schema

package
v0.2.0Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2019 License:MITImports:15Imported by:176

Details

Repository

github.com/rs/rest-layer

Links

Documentation

Overview

Package schema provides a validation framework for the API resources.

This package is part of the rest-layer project. Seehttp://rest-layer.io forfull REST Layer documentation.

Index

Examples

Constants

This section is empty.

Variables

View Source
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(ctxcontext.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}$",},})
View Source
var (// Now is a field hook handler that returns the current time, to be used in// schema with OnInit and OnUpdate.Now = func(ctxcontext.Context, value interface{}) interface{} {returntime.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{},})
View Source
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{},})
View Source
var Tombstone = internal{}

Tombstone is used to mark a field for removal.

Functions

funcVerifyPassword

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

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

Types

typeAllOf

type AllOf []FieldValidator

AllOf validates that all the sub field validators validates. Be aware thatthe order of the validators matter, as the result of one successfulvalidation is passed as input to the next.

func (AllOf)Compile

func (vAllOf) Compile(rcReferenceChecker) (errerror)

Compile implements the ReferenceCompiler interface.

func (AllOf)GetFieldadded inv0.2.0

func (vAllOf) GetField(namestring) *Field

GetField implements the FieldGetter interface. Note that it will return thefirst matching field only.

func (AllOf)Validate

func (vAllOf) Validate(value interface{}) (interface{},error)

Validate ensures that all sub-validators validates. Note the result of onesuccessful validation is passed as input to the next. The result of the firsterror or last successful validation is returned.

func (AllOf)ValidateQueryadded inv0.2.0

func (vAllOf) ValidateQuery(value interface{}) (interface{},error)

ValidateQuery implements schema.FieldQueryValidator interface. Note theresult of one successful validation is passed as input to the next. Theresult of the first error or last successful validation is returned.

typeAnyOf

type AnyOf []FieldValidator

AnyOf validates if any of the sub field validators validates. If any of thesub field validators implements the FieldSerializer interface, the *first*implementation which does not error will be used.

func (AnyOf)Compile

func (vAnyOf) Compile(rcReferenceChecker)error

Compile implements the Compiler interface.

func (AnyOf)GetFieldadded inv0.2.0

func (vAnyOf) GetField(namestring) *Field

GetField implements the FieldGetter interface. Note that it will return thefirst matching field only.

func (AnyOf)LessFuncadded inv0.2.0

func (vAnyOf) LessFunc()LessFunc

LessFunc implements the FieldComparator interface, and returns the firstnon-nil LessFunc or nil.

func (AnyOf)Serializeadded inv0.2.0

func (vAnyOf) Serialize(value interface{}) (interface{},error)

Serialize attempts to serialize the value using the first availableFieldSerializer which does not return an error. If no appropriate serializeris found, the input value is returned.

func (AnyOf)Validate

func (vAnyOf) Validate(value interface{}) (interface{},error)

Validate ensures that at least one sub-validator validates.

func (AnyOf)ValidateQueryadded inv0.2.0

func (vAnyOf) ValidateQuery(value interface{}) (interface{},error)

ValidateQuery implements schema.FieldQueryValidator interface.

typeArray

type Array struct {// Values describes the properties for each array item.ValuesField// MinLen defines the minimum array length (default 0).MinLenint// MaxLen defines the maximum array length (default no limit).MaxLenint}

Array validates array values.

func (*Array)Compile

func (v *Array) Compile(rcReferenceChecker) (errerror)

Compile implements the ReferenceCompiler interface.

func (Array)GetFieldadded inv0.2.0

func (vArray) GetField(namestring) *Field

GetField implements the FieldGetter interface. It will returna Field if name corespond to a legal array index according toparameters set on v.

func (Array)Validate

func (vArray) Validate(value interface{}) (interface{},error)

Validate implements FieldValidator.

func (Array)ValidateQueryadded inv0.2.0

func (vArray) ValidateQuery(value interface{}) (interface{},error)

ValidateQuery implements FieldQueryValidator.

typeBool

type Bool struct {}

Bool validates Boolean based values.

func (Bool)Validate

func (vBool) Validate(value interface{}) (interface{},error)

Validate validates and normalize Boolean based value.

typeBoundaries

type Boundaries struct {Minfloat64Maxfloat64}

Boundaries defines min/max for an integer.

typeCompiler

type Compiler interface {Compile(rcReferenceChecker)error}

Compiler is similar to the Compiler interface, but intended for types that implements, or may hold, areference. All nested types must implement this interface.

typeConnectionadded inv0.2.0

type Connection struct {PathstringFieldstringValidatorValidator}

Connection is a dummy validator to define a weak connection to anotherschema. The query.Projection will treat this validator as an externalresource, and generate a sub-request to fetch the sub-payload.

func (*Connection)Validateadded inv0.2.0

func (v *Connection) Validate(value interface{}) (interface{},error)

Validate implements the FieldValidator interface.

typeDict

type Dict struct {// KeysValidator is the validator to apply on dict keys.KeysValidatorFieldValidator// Values describes the properties for each dict value.ValuesField// MinLen defines the minimum number of fields (default 0).MinLenint// MaxLen defines the maximum number of fields (default no limit).MaxLenint}

Dict validates objects with variadic keys.

Example
package mainimport ("github.com/rs/rest-layer/schema")func main() {_ = schema.Schema{Fields: schema.Fields{"dict": schema.Field{Validator: &schema.Dict{// Limit dict keys to foo and bar keys onlyKeysValidator: &schema.String{Allowed: []string{"foo", "bar"},},// Allow either string or integer as dict valueValues: schema.Field{Validator: &schema.AnyOf{0: &schema.String{},1: &schema.Integer{},},},},},},}}

func (*Dict)Compile

func (v *Dict) Compile(rcReferenceChecker) (errerror)

Compile implements the ReferenceCompiler interface.

func (Dict)GetFieldadded inv0.2.0

func (vDict) GetField(namestring) *Field

GetField implements the FieldGetter interface.

func (Dict)Validate

func (vDict) Validate(value interface{}) (interface{},error)

Validate implements FieldValidator interface.

typeErrorMap

type ErrorMap map[string][]interface{}

ErrorMap contains a map of errors by field name.

func (ErrorMap)Error

func (errErrorMap) Error()string

Error implements the built-in error interface.

func (ErrorMap)Mergeadded inv0.2.0

func (errErrorMap) Merge(otherErrorMap)

Merge copies all errors from other into err.

typeErrorSliceadded inv0.2.0

type ErrorSlice []error

ErrorSlice contains a concatenation of several errors.

func (ErrorSlice)Appendadded inv0.2.0

func (errErrorSlice) Append(othererror)ErrorSlice

Append adds an error to err and returns a new slice if others is not nil. Ifother is another ErrorSlice it is extended so that all elements are appended.

func (ErrorSlice)Erroradded inv0.2.0

func (errErrorSlice) Error()string

typeField

type Field struct {// Description stores a short description of the field useful for automatic// documentation generation.Descriptionstring// Required throws an error when the field is not provided at creation.Requiredbool// 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.ReadOnlybool// 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.Hiddenbool// 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(ctxcontext.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(ctxcontext.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.ParamsParams// 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.HandlerFieldHandler// 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.// @seehttp://research.swtch.com/interfaces for more details.ValidatorFieldValidator// Dependency rejects the field if the schema predicate doesn't match the document.// Use query.MustParsePredicate(`{field: "value"}`) to populate this field.DependencyPredicate// 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.Filterablebool// 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.Sortablebool// 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

func (fField) Compile(rcReferenceChecker)error

Compile implements the ReferenceCompiler interface and recursively compile sub schemasand validators when they implement Compiler interface.

typeFieldComparatoradded inv0.2.0

type FieldComparator interface {// LessFunc returns a valid LessFunc or nil. nil is returned when comparison// is not allowed.LessFunc()LessFunc}

FieldComparator must be implemented by a FieldValidator that is to allowcomparison queries ($gt, $gte, $lt and $lte). The returned LessFunc will beused by the query package's Predicate.Match functions, which is used e.g. bythe internal mem storage backend.

typeFieldGetteradded inv0.2.0

type FieldGetter interface {// GetField returns a Field for the given name if the name is allowed by// the schema. The field is expected to validate query values.//// You may reference a sub-field using dotted notation, e.g. field.subfield.GetField(namestring) *Field}

FieldGetter defines an interface for fetching sub-fields from a Schema orFieldValidator implementation that allows (JSON) object values.

typeFieldHandler

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

FieldHandler is the piece of logic modifying the field value based on passedparameters

typeFieldQueryValidatoradded inv0.2.0

type FieldQueryValidator interface {ValidateQuery(value interface{}) (interface{},error)}

FieldQueryValidator defines an interface for lightweight validation on fieldtypes, without applying constrains on the actual values.

typeFieldSerializer

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 formand it internal storable form. A FieldValidator which implement thisinterface will have its Serialize method called before marshaling.

typeFieldValidator

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

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

typeFieldValidatorFuncadded inv0.2.0

type FieldValidatorFunc func(value interface{}) (interface{},error)

FieldValidatorFunc is an adapter to allow the use of ordinary functions asfield validators. If f is a function with the appropriate signature,FieldValidatorFunc(f) is a FieldValidator that calls f.

func (FieldValidatorFunc)Validateadded inv0.2.0

func (fFieldValidatorFunc) Validate(value interface{}) (interface{},error)

Validate calls f(value).

typeFields

type Fields map[string]Field

Fields defines a map of name -> field pairs

typeFloat

type Float struct {Allowed    []float64Boundaries *Boundaries}

Float validates float based values.

func (Float)LessFuncadded inv0.2.0

func (vFloat) LessFunc()LessFunc

LessFunc implements the FieldComparator interface.

func (Float)Validate

func (vFloat) Validate(value interface{}) (interface{},error)

Validate validates and normalize float based value.

func (Float)ValidateQueryadded inv0.2.0

func (vFloat) ValidateQuery(value interface{}) (interface{},error)

ValidateQuery implements schema.FieldQueryValidator interface

typeIP

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.StoreBinarybool}

IP validates IP values

func (IP)Serialize

func (vIP) Serialize(value interface{}) (interface{},error)

Serialize implements FieldSerializer.

func (IP)Validate

func (vIP) Validate(value interface{}) (interface{},error)

Validate implements FieldValidator

typeInteger

type Integer struct {Allowed    []intBoundaries *Boundaries}

Integer validates integer based values.

func (Integer)LessFuncadded inv0.2.0

func (vInteger) LessFunc()LessFunc

LessFunc implements the FieldComparator interface.

func (Integer)Validate

func (vInteger) Validate(value interface{}) (interface{},error)

Validate validates and normalize integer based value.

func (Integer)ValidateQueryadded inv0.2.0

func (vInteger) ValidateQuery(value interface{}) (interface{},error)

ValidateQuery implements schema.FieldQueryValidator interface

typeLessFuncadded inv0.2.0

type LessFunc func(value, other interface{})bool

LessFunc is a function that returns true only when value is less than other,and false in all other circumstances, including error conditions.

typeNull

type Null []FieldValidator

Null validates that the value is null.

func (Null)Validate

func (vNull) Validate(value interface{}) (interface{},error)

Validate ensures that value is null.

typeObject

type Object struct {Schema *Schema}

Object validates objects which are defined by Schemas.

func (*Object)Compile

func (v *Object) Compile(rcReferenceChecker)error

Compile implements the ReferenceCompiler interface.

func (Object)GetFieldadded inv0.2.0

func (vObject) GetField(namestring) *Field

GetField implements the FieldGetter interface.

func (Object)Validate

func (vObject) Validate(value interface{}) (interface{},error)

Validate implements FieldValidator interface.

typeParam

type Param struct {// Description of the parameterDescriptionstring// Validator to use for this parameterValidatorFieldValidator}

Param define an individual field parameter with its validator

typeParams

type Params map[string]Param

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

typePassword

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

Password crypts a field password using bcrypt algorithm.

func (Password)Validate

func (vPassword) Validate(value interface{}) (interface{},error)

Validate implements FieldValidator interface.

typePredicateadded inv0.2.0

type Predicate interface {Match(payload map[string]interface{})boolPrepare(vValidator)error}

Predicate is an interface matching the query.Predicate type.

funcQ

func Q()Predicate

Q is deprecated, use query.MustParsePredicate instead.

typeReference

type Reference struct {PathstringSchemaValidatorValidator// contains filtered or unexported fields}

Reference validates the ID of a linked resource.

func (*Reference)Compileadded inv0.2.0

func (r *Reference) Compile(rcReferenceChecker)error

Compile validates v.Path against rc and stores the a FieldValidator for later use by v.Validate.

func (Reference)GetFieldadded inv0.2.0

func (rReference) GetField(namestring) *Field

GetField implements the FieldGetter interface.

func (Reference)Validate

func (rReference) Validate(value interface{}) (interface{},error)

Validate validates and sanitizes IDs against the reference path.

typeReferenceCheckeradded inv0.2.0

type ReferenceChecker interface {// ReferenceChecker should return a FieldValidator that can be used for validate that a referenced ID exists and// is of the right format. If there is no resource matching path, nil should e returned.ReferenceChecker(pathstring) (FieldValidator,Validator)}

ReferenceChecker is used to retrieve a FieldValidator that can be used for validating referenced IDs.

typeReferenceCheckerFuncadded inv0.2.0

type ReferenceCheckerFunc func(pathstring)FieldValidator

ReferenceCheckerFunc is an adapter that allows ordinary functions to be used as reference checkers.

func (ReferenceCheckerFunc)ReferenceCheckeradded inv0.2.0

func (fReferenceCheckerFunc) ReferenceChecker(pathstring)FieldValidator

ReferenceChecker calls f(path).

typeSchema

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

Schema defines fields for a document.

func (Schema)Compile

func (sSchema) Compile(rcReferenceChecker)error

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

func (Schema)GetField

func (sSchema) GetField(namestring) *Field

GetField implements the FieldGetter interface.

func (Schema)Prepare

func (sSchema) Prepare(ctxcontext.Context, payload map[string]interface{}, original *map[string]interface{}, replacebool) (changes map[string]interface{}, base map[string]interface{})

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

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

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

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

func (Schema)Validate

func (sSchema) 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 schemaand generate an result document with the changes applied to the base document.All errors in the process are reported in the returned errs value.

typeString

type String struct {RegexpstringAllowed []stringMaxLenintMinLenint// contains filtered or unexported fields}

String validates string based values

func (*String)Compile

func (v *String) Compile(rcReferenceChecker) (errerror)

Compile compiles and validate regexp if any.

func (String)Validate

func (vString) Validate(value interface{}) (interface{},error)

Validate validates and normalize string based value.

func (String)ValidateQueryadded inv0.2.0

func (vString) ValidateQuery(value interface{}) (interface{},error)

ValidateQuery implements schema.FieldQueryValidator interface

typeTime

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

func (v *Time) Compile(rcReferenceChecker)error

Compile the time formats.

func (Time)LessFuncadded inv0.2.0

func (vTime) LessFunc()LessFunc

LessFunc implements the FieldComparator interface.

func (Time)Validate

func (vTime) Validate(value interface{}) (interface{},error)

Validate validates and normalize time based value.

func (Time)ValidateQueryadded inv0.2.0

func (vTime) ValidateQuery(value interface{}) (interface{},error)

ValidateQuery implements schema.FieldQueryValidator interface

typeURL

type URL struct {AllowRelativeboolAllowLocaleboolAllowNonHTTPboolAllowedSchemes []string}

URL validates URLs values.

func (URL)Validate

func (vURL) Validate(value interface{}) (interface{},error)

Validate validates URL values.

typeValidator

type Validator interface {GetField(namestring) *FieldPrepare(ctxcontext.Context, payload map[string]interface{}, original *map[string]interface{}, replacebool) (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.

Source Files

View all Source files

Directories

PathSynopsis
Package encoding is the intended hierarchy location for encoding Schema to other formats.
Package encoding is the intended hierarchy location for encoding Schema to other formats.
jsonschema
Package jsonschema provides JSON Schema Draft 4 encoding support for schema.Schema.
Package jsonschema provides JSON Schema Draft 4 encoding support for schema.Schema.
Package query provides tools to query a schema defined by github.com/rs/schema.
Package query provides tools to query a schema defined by github.com/rs/schema.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp