schema

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Mar 11, 2024 License: MIT Imports: 6 Imported by: 0

README

toml-schema

toml-schema utilizes TOML to define validation schemas for input in a simple manner. Under the hood, we generate a map[string]interface{} rule definition that can be used by go-playground/validator.

It was created for use in the sabaresu serverless framework to enable configuration-based validation.

Getting Started

Schema

Schema are written in TOML, like so:

# key = "validators"
name = "string,required,min=1,max=128"
age = "number,required,int,min=1,max=150"
ecash = "number,required,min=0,max=150000"
is_cool = "boolean,required"

# A nested map can be added with [key]
[location]
address1 = "string,required"
address2 = "string,required"

# A slice is added with [[key]]

[[ships]]
id = "string,required,uuid"
make = "string,oneof=x-wing y-wing a-wing millenium falcon tie-fighter"

Validate

To validate data against your schema and constraints:

import (
    "github.com/Phamiliarize/toml-schema"
    "github.com/go-playground/validator/v10"
)

// Use any v10 instance of a go-playground/validator
// This allows you to extend the potential validators
v := schema.NewValidator(validator.New())
err := v.LoadSchema("mySchema", `test = "string,required"`)
if err != nil {
    panic(err)
}

// Returns a map[string]validation.ValidationErrors
err := v.ValidateSchema("mySchema", myData)
if err != nil {
    panic(err)
}

Basic Types & Constraints

The supported constraints/validations are basically inline with go-playground/validator but since the end usecase is for JSON and Lua we require a "type constraint" on all fields.

Every field must start with a basic type. The basic types supported are:

Type GoLang Type Validators
string string string
number float64 or int number
boolean bool boolean

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Validator added in v0.1.1

type Validator struct {
	Validator *validate.Validate
	// contains filtered or unexported fields
}

func NewValidator

func NewValidator(v *validate.Validate) Validator

func (*Validator) LoadSchema added in v0.1.1

func (v *Validator) LoadSchema(name string, tomlSchema string) error

Loads schema file and passes it through recursive function to generate a rules map

func (*Validator) ValidateSchema added in v0.1.1

func (v *Validator) ValidateSchema(name string, data map[string]interface{}) map[string]interface{}

Jump to

Keyboard shortcuts

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