Documentation
¶
Overview ¶
Package queryfy provides schema validation and querying for dynamic data in Go.
Queryfy is designed to work with map[string]interface{} data structures commonly found in JSON APIs, configuration files, and other dynamic contexts.
Basic usage:
schema := queryfy.Object().
Field("id", queryfy.String().Required()).
Field("amount", queryfy.Number().Min(0))
data := map[string]interface{}{
"id": "order-123",
"amount": 99.99,
}
if err := queryfy.Validate(data, schema); err != nil {
// Handle validation error
}
// Query the data
amount, _ := queryfy.Query(data, "amount")
types.go - Updated with DateTime, Dependent, and Transform types
Index ¶
- func ConvertStringToNumber(str string) (float64, bool)
- func ConvertToString(value interface{}) (string, bool)
- func MustValidate(data interface{}, schema Schema)
- func Query(data interface{}, queryStr string) (interface{}, error)
- func Validate(data interface{}, schema Schema) error
- func ValidateValue(value interface{}, expectedType SchemaType, ctx *ValidationContext) bool
- func ValidateWithMode(data interface{}, schema Schema, mode ValidationMode) error
- func WrapError(err error, path string) error
- type BaseSchema
- type FieldError
- type Option
- type Schema
- type SchemaType
- type TransformableSchema
- type TransformationRecord
- type Transformer
- type TransformerFunc
- type ValidationContext
- func (c *ValidationContext) AddError(message string, value interface{})
- func (c *ValidationContext) AddFieldError(err FieldError)
- func (c *ValidationContext) CurrentPath() string
- func (c *ValidationContext) Error() error
- func (c *ValidationContext) Errors() []FieldError
- func (c *ValidationContext) HasErrors() bool
- func (c *ValidationContext) HasTransformations() bool
- func (c *ValidationContext) Mode() ValidationMode
- func (c *ValidationContext) PopPath()
- func (c *ValidationContext) PushIndex(index int)
- func (c *ValidationContext) PushPath(segment string)
- func (c *ValidationContext) RecordTransformation(original, result interface{}, transformType string)
- func (c *ValidationContext) Transformations() []TransformationRecord
- func (c *ValidationContext) WithIndex(index int, fn func())
- func (c *ValidationContext) WithPath(segment string, fn func())
- type ValidationError
- type ValidationMode
- type Validator
- type ValidatorFunc
- type WithTransform
- func (s *WithTransform) AddTransformer(t TransformerFunc) *WithTransform
- func (s *WithTransform) Type() SchemaType
- func (s *WithTransform) Validate(value interface{}, ctx *ValidationContext) error
- func (s *WithTransform) ValidateAndTransform(value interface{}, ctx *ValidationContext) (interface{}, error)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ConvertStringToNumber ¶
ConvertStringToNumber attempts to convert a string to a number. Returns the number and true if successful, 0 and false otherwise.
func ConvertToString ¶
ConvertToString attempts to convert a value to string. Returns the string and true if successful, empty string and false otherwise.
func MustValidate ¶
func MustValidate(data interface{}, schema Schema)
MustValidate validates data against a schema and panics on error. This is useful in initialization code where validation errors are fatal.
func Query ¶
Query executes a query against the data and returns the result. Supports dot notation and array indexing:
- "name" - returns the value of field "name"
- "user.email" - returns nested field value
- "items[0]" - returns first element of array
- "items[0].price" - returns field from array element
func Validate ¶
Validate validates data against a schema. Returns a ValidationError containing all validation failures, or nil if valid.
func ValidateValue ¶
func ValidateValue(value interface{}, expectedType SchemaType, ctx *ValidationContext) bool
ValidateValue is a helper function that validates a single value against its expected type. It handles type checking and conversion based on the validation mode.
func ValidateWithMode ¶
func ValidateWithMode(data interface{}, schema Schema, mode ValidationMode) error
ValidateWithMode validates data against a schema with a specific validation mode.
Types ¶
type BaseSchema ¶
type BaseSchema struct {
SchemaType SchemaType // Changed from schemaType to SchemaType to make it accessible
// contains filtered or unexported fields
}
BaseSchema provides common functionality for all schema types. It should be embedded in concrete schema implementations.
func (*BaseSchema) CheckRequired ¶
func (s *BaseSchema) CheckRequired(value interface{}, ctx *ValidationContext) bool
CheckRequired checks if a required field is present and not nil. Returns true if validation should continue, false if it should stop.
func (*BaseSchema) IsNullable ¶
func (s *BaseSchema) IsNullable() bool
IsNullable returns true if the field can be null.
func (*BaseSchema) IsRequired ¶
func (s *BaseSchema) IsRequired() bool
IsRequired returns true if the field is required.
func (*BaseSchema) SetNullable ¶
func (s *BaseSchema) SetNullable(nullable bool)
SetNullable sets whether the field can be null.
func (*BaseSchema) SetRequired ¶
func (s *BaseSchema) SetRequired(required bool)
SetRequired sets whether the field is required.
type FieldError ¶
type FieldError struct {
// Path is the field path where the error occurred (e.g., "user.email" or "items[0].price")
Path string
// Message describes what validation failed
Message string
// Value is the actual value that failed validation (optional)
Value interface{}
}
FieldError represents a validation error for a specific field.
func NewFieldError ¶
func NewFieldError(path, message string, value interface{}) FieldError
NewFieldError creates a new FieldError.
func (FieldError) Error ¶
func (e FieldError) Error() string
Error implements the error interface for FieldError.
func (FieldError) String ¶
func (e FieldError) String() string
String returns a string representation of the field error.
type Option ¶
type Option func(interface{})
Option represents a configuration option for validators.
type Schema ¶
type Schema interface {
// Validate validates a value against this schema.
// It should add any validation errors to the context.
// Returns an error only for unexpected failures (not validation failures).
Validate(value interface{}, ctx *ValidationContext) error
// Type returns the schema type.
Type() SchemaType
}
Schema represents a validation schema. All schema types must implement this interface.
type SchemaType ¶
type SchemaType string
SchemaType represents the type of a schema.
const ( // TypeString represents a string schema TypeString SchemaType = "string" // TypeNumber represents a number schema TypeNumber SchemaType = "number" // TypeBool represents a boolean schema TypeBool SchemaType = "boolean" // TypeObject represents an object schema TypeObject SchemaType = "object" // TypeArray represents an array schema TypeArray SchemaType = "array" // TypeAny represents a schema that accepts any type TypeAny SchemaType = "any" // TypeCustom represents a custom validator TypeCustom SchemaType = "custom" // TypeComposite represents a composite schema (AND/OR/NOT) TypeComposite SchemaType = "composite" // TypeDateTime represents a date/time schema TypeDateTime SchemaType = "datetime" // TypeDependent represents a dependent field schema TypeDependent SchemaType = "dependent" // TypeTransform represents a transformation schema TypeTransform SchemaType = "transform" )
func (SchemaType) String ¶
func (t SchemaType) String() string
String returns the string representation of a SchemaType.
type TransformableSchema ¶ added in v0.2.0
type TransformableSchema interface {
Schema
// ValidateAndTransform returns the transformed value and any validation error
ValidateAndTransform(value interface{}, ctx *ValidationContext) (interface{}, error)
}
TransformableSchema represents a schema that can apply transformations.
type TransformationRecord ¶ added in v0.2.0
type TransformationRecord struct {
Path string
Original interface{}
Result interface{}
Type string
}
TransformationRecord records a transformation that was applied.
type Transformer ¶ added in v0.2.0
type Transformer interface {
// Transform applies the transformation to a value
Transform(value interface{}) (interface{}, error)
}
Transformer represents a function that can transform values. This is defined here to avoid circular dependencies.
type TransformerFunc ¶ added in v0.2.0
type TransformerFunc func(value interface{}) (interface{}, error)
TransformerFunc is a function that transforms a value. It returns the transformed value and any error.
type ValidationContext ¶
type ValidationContext struct {
// contains filtered or unexported fields
}
ValidationContext maintains state during validation. It tracks the current path and accumulates errors.
func NewValidationContext ¶
func NewValidationContext(mode ValidationMode) *ValidationContext
NewValidationContext creates a new validation context.
func (*ValidationContext) AddError ¶
func (c *ValidationContext) AddError(message string, value interface{})
AddError adds an error at the current path.
func (*ValidationContext) AddFieldError ¶
func (c *ValidationContext) AddFieldError(err FieldError)
AddFieldError adds a pre-constructed field error.
func (*ValidationContext) CurrentPath ¶
func (c *ValidationContext) CurrentPath() string
CurrentPath returns the current field path as a string.
func (*ValidationContext) Error ¶
func (c *ValidationContext) Error() error
Error returns a ValidationError if there are any errors, nil otherwise.
func (*ValidationContext) Errors ¶
func (c *ValidationContext) Errors() []FieldError
Errors returns all accumulated errors.
func (*ValidationContext) HasErrors ¶
func (c *ValidationContext) HasErrors() bool
HasErrors returns true if any errors have been added.
func (*ValidationContext) HasTransformations ¶ added in v0.2.0
func (c *ValidationContext) HasTransformations() bool
HasTransformations returns true if any transformations were applied.
func (*ValidationContext) Mode ¶
func (c *ValidationContext) Mode() ValidationMode
Mode returns the validation mode.
func (*ValidationContext) PopPath ¶
func (c *ValidationContext) PopPath()
PopPath removes the last path segment.
func (*ValidationContext) PushIndex ¶
func (c *ValidationContext) PushIndex(index int)
PushIndex adds an array index to the current path.
func (*ValidationContext) PushPath ¶
func (c *ValidationContext) PushPath(segment string)
PushPath adds a path segment to the current path.
func (*ValidationContext) RecordTransformation ¶ added in v0.2.0
func (c *ValidationContext) RecordTransformation(original, result interface{}, transformType string)
RecordTransformation records that a transformation was applied.
func (*ValidationContext) Transformations ¶ added in v0.2.0
func (c *ValidationContext) Transformations() []TransformationRecord
Transformations returns all recorded transformations.
func (*ValidationContext) WithIndex ¶
func (c *ValidationContext) WithIndex(index int, fn func())
WithIndex executes a function with an array index pushed onto the context. The index is automatically popped when the function returns.
func (*ValidationContext) WithPath ¶
func (c *ValidationContext) WithPath(segment string, fn func())
WithPath executes a function with a path segment pushed onto the context. The path is automatically popped when the function returns.
type ValidationError ¶
type ValidationError struct {
Errors []FieldError
}
ValidationError represents one or more validation failures. It contains a slice of FieldError that provides detailed information about each validation failure.
func NewValidationError ¶
func NewValidationError(errors ...FieldError) *ValidationError
NewValidationError creates a new ValidationError with the given field errors.
func (*ValidationError) Add ¶
func (e *ValidationError) Add(path, message string, value interface{})
Add adds a field error to the validation error.
func (*ValidationError) AddError ¶
func (e *ValidationError) AddError(err FieldError)
AddError adds an existing FieldError to the validation error.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
Error returns a string representation of all validation errors.
func (*ValidationError) HasErrors ¶
func (e *ValidationError) HasErrors() bool
HasErrors returns true if there are any validation errors.
type ValidationMode ¶
type ValidationMode int
ValidationMode determines how strict the validation is.
const ( // Strict mode requires exact schema compliance. // Extra fields in objects will cause validation to fail. Strict ValidationMode = iota // Loose mode allows extra fields and safe type coercion. // Extra fields in objects are ignored. // Safe type coercions are applied (e.g., "123" -> 123). Loose )
func (ValidationMode) String ¶
func (m ValidationMode) String() string
String returns the string representation of a ValidationMode.
type Validator ¶
type Validator struct {
// contains filtered or unexported fields
}
Validator wraps a schema with configuration options.
func NewValidator ¶
NewValidator creates a new validator with a schema. The validator can be configured with different modes and options.
type ValidatorFunc ¶
type ValidatorFunc func(value interface{}) error
ValidatorFunc is a function that validates a value. It should return an error if validation fails, nil otherwise.
type WithTransform ¶ added in v0.2.0
type WithTransform struct {
Schema
// contains filtered or unexported fields
}
WithTransform wraps a schema to add transformation capability.
func NewWithTransform ¶ added in v0.2.0
func NewWithTransform(schema Schema) *WithTransform
NewWithTransform creates a new schema with transformation support.
func (*WithTransform) AddTransformer ¶ added in v0.2.0
func (s *WithTransform) AddTransformer(t TransformerFunc) *WithTransform
AddTransformer adds a transformer to the pipeline.
func (*WithTransform) Type ¶ added in v0.2.0
func (s *WithTransform) Type() SchemaType
Type returns the underlying schema type.
func (*WithTransform) Validate ¶ added in v0.2.0
func (s *WithTransform) Validate(value interface{}, ctx *ValidationContext) error
Validate applies transformations then validates.
func (*WithTransform) ValidateAndTransform ¶ added in v0.2.0
func (s *WithTransform) ValidateAndTransform(value interface{}, ctx *ValidationContext) (interface{}, error)
ValidateAndTransform validates and returns the transformed value.
Directories
¶
| Path | Synopsis |
|---|---|
|
datetime.go - Date/Time validation builder for Queryfy
|
datetime.go - Date/Time validation builder for Queryfy |
|
transformers
common.go - Common transformation functions
|
common.go - Common transformation functions |
|
examples
|
|
|
basic
command
|
|
|
custom-validators
command
|
|
|
datetime
command
|
|
|
dependent-fields
command
|
|
|
transformation/api
command
|
|
|
transformation/basic
command
|
|
|
transformation/phone
command
|
|
|
internal
|
|
|
cache
Package cache provides a simple thread-safe cache implementation.
|
Package cache provides a simple thread-safe cache implementation. |
|
typeutil
Package typeutil provides type checking and conversion utilities.
|
Package typeutil provides type checking and conversion utilities. |
|
Package query provides a simple query language for navigating data structures.
|
Package query provides a simple query language for navigating data structures. |