desire

package module
v0.0.0-...-1e98856 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2022 License: MIT Imports: 7 Imported by: 0

README

go-desire

Flexible validation library designed for testing.

Example

package main

import (
	"fmt"
	"sort"

	"github.com/morikuni/go-desire"
)

func Example() {
	val := map[string]any{
		"id":   1,
		"name": "david",
		"age":  20,
		"friends": []map[string]any{
			{
				"id":   2,
				"name": "bob",
			},
			{
				"id":   4,
				"name": "charlie",
			},
		},
	}

	rejections := desire.Desire(val, desire.Partial{
		"id":   desire.NotZeroT[int](),
		"name": desire.OneOf("alice", "bob"),
		// not validate "age"
		"friends": desire.List{
			desire.NotZero(),
			map[string]any{
				"id":   3,
				"name": "charlie",
			},
		},
	})

	sort.Slice(rejections, func(i, j int) bool {
		return rejections[i].Path.String() < rejections[j].Path.String()
	})
	for _, r := range rejections {
		fmt.Println(r)
	}

	// Output:
	// friends.1.id: expected 3 but got 4
	// name: expected one of [alice bob] but got david
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FormatRejections

func FormatRejections(rs []Rejection) string

func Validate

func Validate(ctx ValidationContext, got, desire any)

Types

type Fields

type Fields map[string]any

func (Fields) Validate

func (fs Fields) Validate(ctx ValidationContext, got any)

type List

type List []any

func (List) Validate

func (ls List) Validate(ctx ValidationContext, got any)

type Partial

type Partial map[any]any

func (Partial) Validate

func (p Partial) Validate(ctx ValidationContext, got any)

type Path

type Path []string

func (Path) String

func (p Path) String() string

type Rejection

type Rejection struct {
	Path   Path
	Reason string
}

func Desire

func Desire(got, desire any) []Rejection

func (Rejection) String

func (r Rejection) String() string

type ValidationContext

type ValidationContext interface {
	Reject(reason string)
	Rejectf(format string, args ...interface{})
	WithField(field string) ValidationContext
}

type Validator

type Validator interface {
	Validate(ValidationContext, any)
}

func All

func All(vs ...Validator) Validator

func Any

func Any() Validator

func NotZero

func NotZero() Validator

func NotZeroT

func NotZeroT[T comparable]() Validator

func OneOf

func OneOf(candidates ...any) Validator

type ValidatorFunc

type ValidatorFunc func(ValidationContext, any)

func (ValidatorFunc) Validate

func (f ValidatorFunc) Validate(ctx ValidationContext, got any)

Jump to

Keyboard shortcuts

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