diff --git a/builder.go b/builder.go index 0b074f8..601f622 100644 --- a/builder.go +++ b/builder.go @@ -49,6 +49,19 @@ func (c Configurator[T]) add(fn shared.ValidationFn) { c.b.v.validators[t] = append(c.b.v.validators[t], fn) } +// describe returns the registration of the constraints of the rules of T, nil under the struct level When: +// the conditional rules aren't described. +func (c Configurator[T]) describe() shared.Describe { + if c.b.when != nil { + return nil + } + v, t := c.b.v, reflect.TypeFor[T]() + return func(constraint shared.Constraint) { + constraint.Struct = t + v.constraints[t] = append(v.constraints[t], constraint) + } +} + // When returns a Configurator whose rules are applied only if fn returns true. // Conditions of chained When calls are combined with AND. func (c Configurator[T]) When(fn func(ctx context.Context, obj *T) bool) Configurator[T] { @@ -103,7 +116,7 @@ func (c Configurator[T]) Custom(fn func(ctx context.Context, h shared.StructCust // b.Field(&m.Name).As(str.Of), b.Field(&m.Discount).As(num.Ptr). func (c Configurator[T]) Field[F any](fieldPtr *F) *shared.Field[F] { field := c.field(fieldPtr) - return shared.NewValueField[F](field, c.b.v.helper, c.field, c.add) + return shared.NewValueField[F](field, c.b.v.helper, c.field, c.add, c.describe()) } // Slice returns the configurator of the slice field with the rules of the slice itself, @@ -111,12 +124,12 @@ func (c Configurator[T]) Field[F any](fieldPtr *F) *shared.Field[F] { // A pointer to a slice field is converted from its field: b.Field(&m.Tags).As(shared.SlicePtr). func (c Configurator[T]) Slice[E any](sliceFieldPtr *[]E) *shared.SliceFieldConfigurator[E] { field := c.field(sliceFieldPtr) - return shared.NewSliceFieldConfigurator[E](field, c.b.v.helper, c.field, c.add) + return shared.NewSliceFieldConfigurator[E](field, c.b.v.helper, c.field, c.add, c.describe()) } // Map returns the configurator of the map field with the rules of the map itself, EachKey and EachValue: // b.Map(&m.Labels).MaxLen(10).EachKey(func(k *shared.Field[string]) { k.As(str.Of).Hostname() }). func (c Configurator[T]) Map[K comparable, V any](mapFieldPtr *map[K]V) *shared.MapFieldConfigurator[K, V] { field := c.field(mapFieldPtr) - return shared.NewMapFieldConfigurator[K, V](field, c.b.v.helper, c.field, c.add) + return shared.NewMapFieldConfigurator[K, V](field, c.b.v.helper, c.field, c.add, c.describe()) } diff --git a/constraints_test.go b/constraints_test.go new file mode 100644 index 0000000..8cb5f4f --- /dev/null +++ b/constraints_test.go @@ -0,0 +1,123 @@ +package valigo + +import ( + "context" + "reflect" + "regexp" + "testing" + "time" + + "github.com/stretchr/testify/assert" + + "github.com/insei/valigo/eq" + "github.com/insei/valigo/num" + "github.com/insei/valigo/shared" + "github.com/insei/valigo/str" +) + +type constraintsAddress struct { + City string +} + +type constraintsModel struct { + Name string + Code string + Email *string + Age int + Rate *float64 + Role string + Kind string + Day string + Tags []string + Roles []string + Labels map[string]int + Note string + Address *constraintsAddress +} + +type described struct { + Field string + Path []string + Keyword string + Value any +} + +func describedOf(constraints []shared.Constraint) []described { + result := make([]described, len(constraints)) + for i, c := range constraints { + result[i] = described{Field: c.Field.GetStructPath(), Path: c.Path, Keyword: c.Keyword, Value: c.Value} + } + return result +} + +func TestConstraints(t *testing.T) { + v := New() + Configure[constraintsModel](v, func(b Configurator[constraintsModel], m *constraintsModel) { + b.Field(&m.Name).As(str.Of).Trim().Required().MaxRunes(64) + b.Field(&m.Code).As(str.Of).MinRunes(2).MaxLen(8).Regexp(regexp.MustCompile(`^[A-Z]+$`)).Prefix("A.") + b.Field(&m.Email).As(str.Of).Email() + b.Field(&m.Age).As(num.Of).Required().AnyOfInterval(18, 120) + b.Field(&m.Rate).As(num.Ptr).Min(0).Max(1) + b.Field(&m.Role).As(eq.Of).OneOf("admin", "user") + b.Field(&m.Kind).As(eq.Of).Equal("person") + b.Field(&m.Day).As(str.Of).Datetime(time.DateOnly).Datetime(time.Kitchen) + b.Slice(&m.Tags).As(str.Slice).Required().MaxLen(5).Each(func(tag *str.BaseConfigurator) { tag.MaxRunes(16) }) + b.Slice(&m.Roles).As(eq.Slice).MinLen(1).Unique() + b.Map(&m.Labels).Required().MaxLen(3). + EachKey(func(k *shared.Field[string]) { k.As(str.Of).Hostname() }). + EachValue(func(v *shared.Field[int]) { v.As(num.Of).Min(1) }) + b.Field(&m.Note).As(str.Of).When(func(context.Context, string) bool { return true }).MaxLen(10) + b.Field(&m.Address.City).As(str.Of).Required() + b.When(func(context.Context, *constraintsModel) bool { return true }).Field(&m.Note).As(str.Of).MaxLen(20) + }) + items, props, names := []string{"items"}, []string{"additionalProperties"}, []string{"propertyNames"} + assert.Equal(t, []described{ + {"Name", nil, "required", true}, + {"Code", nil, "minLength", 2}, + {"Code", nil, "maxLength", 8}, + {"Code", nil, "pattern", "^[A-Z]+$"}, + {"Code", nil, "pattern", `^A\.`}, + {"Email", nil, "format", "email"}, + {"Age", nil, "required", true}, + {"Age", nil, "minimum", 18}, + {"Age", nil, "maximum", 120}, + {"Rate", nil, "minimum", 0.0}, + {"Rate", nil, "maximum", 1.0}, + {"Role", nil, "enum", []any{"admin", "user"}}, + {"Kind", nil, "const", "person"}, + {"Day", nil, "format", "date"}, + {"Tags", nil, "required", true}, + {"Tags", nil, "minItems", 1}, + {"Tags", nil, "maxItems", 5}, + {"Tags", items, "maxLength", 16}, + {"Roles", nil, "minItems", 1}, + {"Roles", nil, "uniqueItems", true}, + {"Labels", nil, "required", true}, + {"Labels", nil, "minProperties", 1}, + {"Labels", nil, "maxProperties", 3}, + {"Labels", names, "format", "hostname"}, + {"Labels", props, "minimum", 1}, + {"Address.City", nil, "required", true}, + {"Address.City", nil, "minLength", 1}, + }, describedOf(v.Constraints())) + for _, c := range v.Constraints() { + assert.Equal(t, reflect.TypeFor[constraintsModel](), c.Struct) + } + + Configure[constraintsModel](v, func(b Configurator[constraintsModel], m *constraintsModel) { + b.Field(&m.Email).As(str.Of).Email() + }) + assert.Len(t, v.Constraints(), 1, "Configure replaces the constraints") +} + +func TestConstraintsOrder(t *testing.T) { + v := New() + Configure[constraintsModel](v, func(b Configurator[constraintsModel], m *constraintsModel) { + b.Field(&m.Name).As(str.Of).Required() + }) + Configure[constraintsAddress](v, func(b Configurator[constraintsAddress], a *constraintsAddress) { + b.Field(&a.City).As(str.Of).Required() + }) + assert.Equal(t, "City", v.Constraints()[0].Field.GetStructPath(), "the structs are sorted by name") + assert.Equal(t, "Name", v.Constraints()[2].Field.GetStructPath()) +} diff --git a/eq/base.go b/eq/base.go index 393e86b..4ee23ad 100644 --- a/eq/base.go +++ b/eq/base.go @@ -44,6 +44,7 @@ func Ptr[T comparable](f *shared.Field[*T]) *BaseConfigurator[T] { // Required checks if the value is not zero, for pointer fields checks if the pointer is not nil. func (i *BaseConfigurator[T]) Required() *BaseConfigurator[T] { + i.f.Schema(shared.KeywordRequired, true) optional := i.optional var zero T i.f.RequiredMsg(func(v T) bool { return optional || v != zero }, shared.M("value.required", requiredLocaleKey)) @@ -52,6 +53,7 @@ func (i *BaseConfigurator[T]) Required() *BaseConfigurator[T] { // OneOf checks if the value is one of the allowed values. func (i *BaseConfigurator[T]) OneOf(allowed ...T) *BaseConfigurator[T] { + i.f.Schema("enum", shared.Values(allowed)) i.f.CheckMsg(func(v T) bool { return slices.Contains(allowed, v) }, shared.M("value.one_of", oneOfLocaleKey, shared.P("values", allowed))) return i } @@ -64,6 +66,7 @@ func (i *BaseConfigurator[T]) NotOneOf(forbidden ...T) *BaseConfigurator[T] { // Equal checks if the value is equal to expected, e.g. Equal(true) for an accepted agreement. func (i *BaseConfigurator[T]) Equal(expected T) *BaseConfigurator[T] { + i.f.Schema("const", expected) i.f.CheckMsg(func(v T) bool { return v == expected }, shared.M("value.equal", equalLocaleKey, shared.P("value", expected))) return i } diff --git a/eq/slice.go b/eq/slice.go index 74a65af..5bb1280 100644 --- a/eq/slice.go +++ b/eq/slice.go @@ -38,6 +38,7 @@ func (s *SliceConfigurator[E]) OneOf(allowed ...E) *SliceConfigurator[E] { // Unique checks that the slice has no duplicate elements, the error value is the first duplicate. // Slices up to 32 elements are checked without allocations. func (s *SliceConfigurator[E]) Unique() *SliceConfigurator[E] { + s.Slice().Schema("uniqueItems", true) msg := shared.M("value.unique", uniqueLocaleKey) s.Slice().Custom(func(ctx context.Context, h *shared.FieldCustomHelper, elems shared.Elems[E]) []shared.Error { if dup, ok := duplicate(elems); ok { diff --git a/num/base.go b/num/base.go index 13efbdc..fcc397e 100644 --- a/num/base.go +++ b/num/base.go @@ -49,6 +49,7 @@ func Ptr[N Number](f *shared.Field[*N]) *BaseConfigurator[N] { // Required checks if the number is not zero, for pointer fields checks if the pointer is not nil. func (i *BaseConfigurator[N]) Required() *BaseConfigurator[N] { + i.f.Schema(shared.KeywordRequired, true) optional := i.optional i.f.RequiredMsg(func(v N) bool { return optional || v != 0 }, shared.M("number.required", requiredLocaleKey)) return i @@ -56,12 +57,14 @@ func (i *BaseConfigurator[N]) Required() *BaseConfigurator[N] { // Max checks if the number is not greater than maxNum. func (i *BaseConfigurator[N]) Max(maxNum N) *BaseConfigurator[N] { + i.f.Schema("maximum", maxNum) i.f.CheckMsg(func(v N) bool { return v <= maxNum }, shared.M("number.max", maxLocaleKey, shared.P("max", maxNum))) return i } // Min checks if the number is not less than minNum. func (i *BaseConfigurator[N]) Min(minNum N) *BaseConfigurator[N] { + i.f.Schema("minimum", minNum) i.f.CheckMsg(func(v N) bool { return v >= minNum }, shared.M("number.min", minLocaleKey, shared.P("min", minNum))) return i } @@ -82,24 +85,28 @@ func (i *BaseConfigurator[N]) MaxField(other *N) *BaseConfigurator[N] { // AnyOf checks if the number is one of the allowed values. func (i *BaseConfigurator[N]) AnyOf(allowed ...N) *BaseConfigurator[N] { + i.f.Schema("enum", shared.Values(allowed)) i.f.CheckMsg(func(v N) bool { return slices.Contains(allowed, v) }, shared.M("number.any_of", anyOfLocaleKey, shared.P("values", allowed))) return i } // AnyOfInterval checks if the number is within [begin, end] interval, both ends inclusive. func (i *BaseConfigurator[N]) AnyOfInterval(begin, end N) *BaseConfigurator[N] { + i.f.Schema("minimum", begin).Schema("maximum", end) i.f.CheckMsg(func(v N) bool { return v >= begin && v <= end }, shared.M("number.interval", anyOfIntervalLocalKey, shared.P("min", begin), shared.P("max", end))) return i } // Latitude checks if the number is a latitude in degrees, within [-90, 90]. func (i *BaseConfigurator[N]) Latitude() *BaseConfigurator[N] { + i.f.Schema("minimum", -90).Schema("maximum", 90) i.f.CheckMsg(func(v N) bool { return float64(v) >= -90 && float64(v) <= 90 }, shared.M("number.latitude", latitudeLocaleKey)) return i } // Longitude checks if the number is a longitude in degrees, within [-180, 180]. func (i *BaseConfigurator[N]) Longitude() *BaseConfigurator[N] { + i.f.Schema("minimum", -180).Schema("maximum", 180) i.f.CheckMsg(func(v N) bool { return float64(v) >= -180 && float64(v) <= 180 }, shared.M("number.longitude", longitudeLocaleKey)) return i } diff --git a/shared/convert.go b/shared/convert.go index fc0df5f..cdf9967 100644 --- a/shared/convert.go +++ b/shared/convert.go @@ -25,7 +25,7 @@ func (s *SliceFieldConfigurator[E]) As[R any](conv func(s *SliceFieldConfigurato // Use it in conversions of pointer fields, e.g. num.Ptr is num.Of of the dereferenced field. func Deref[T any](f *Field[*T]) *Field[T] { add := f.add - return &Field[T]{field: f.field, h: f.h, fields: f.fields, add: func(fn checkFn[T]) { + return &Field[T]{field: f.field, h: f.h, fields: f.fields, schema: f.schema, add: func(fn checkFn[T]) { add(func(ctx context.Context, h Helper, obj any, v **T, errs []Error) []Error { var p *T if v != nil { @@ -44,7 +44,7 @@ func Retype[T, U any](f *Field[T]) *Field[U] { } mustLayout[U](f.field, reflect.TypeFor[T]()) add := f.add - return &Field[U]{field: f.field, h: f.h, fields: f.fields, add: func(fn checkFn[U]) { + return &Field[U]{field: f.field, h: f.h, fields: f.fields, schema: f.schema, add: func(fn checkFn[U]) { add(func(ctx context.Context, h Helper, obj any, v *T, errs []Error) []Error { return fn(ctx, h, obj, (*U)(unsafe.Pointer(v)), errs) }) @@ -57,7 +57,7 @@ func RetypeSlice[E, U any](s *SliceFieldConfigurator[E]) *SliceFieldConfigurator if same, ok := any(s).(*SliceFieldConfigurator[U]); ok { return same } - return &SliceFieldConfigurator[U]{field: s.field, h: s.h, fields: s.fields, get: elemsGetter[U](s.field), add: s.add} + return &SliceFieldConfigurator[U]{field: s.field, h: s.h, fields: s.fields, get: elemsGetter[U](s.field), add: s.add, schema: s.schema} } // SlicePtr converts the field of a pointer to a slice, *[]E, to the slice configurator, a nil pointer is absent: @@ -66,7 +66,7 @@ func SlicePtr[E any](f *Field[*[]E]) *SliceFieldConfigurator[E] { if f.root == nil { panic(fmt.Sprintf("valigo: SlicePtr of field %s must be called before When and other conversions", f.field.GetStructPath())) } - return NewSliceFieldConfigurator[E](f.field, f.h, f.fields, f.root) + return NewSliceFieldConfigurator[E](f.field, f.h, f.fields, f.root, f.rootDescribe) } // SliceRules are the rules of the slice itself for the typed slice configurators, S is the type of the configurator. diff --git a/shared/convert_test.go b/shared/convert_test.go index 54e5982..f30fc30 100644 --- a/shared/convert_test.go +++ b/shared/convert_test.go @@ -31,7 +31,7 @@ func (t *typedSlice) NotEmpty() *typedSlice { func TestFieldAs(t *testing.T) { var r rules - f := NewValueField[string](sampleField(t, "Text"), pathHelper{}, sampleFields, r.add) + f := NewValueField[string](sampleField(t, "Text"), pathHelper{}, sampleFields, r.add, nil) got := f.As(func(f *Field[string]) *Field[string] { return f.Check(notEmpty, "required") }) assert.Same(t, f, got) assert.Len(t, r.validate(&sample{}), 1) @@ -39,7 +39,7 @@ func TestFieldAs(t *testing.T) { func TestDeref(t *testing.T) { var r rules - NewValueField[*string](sampleField(t, "TextPtr"), pathHelper{}, sampleFields, r.add).As(Deref).Required(notEmpty, "required") + NewValueField[*string](sampleField(t, "TextPtr"), pathHelper{}, sampleFields, r.add, nil).As(Deref).Required(notEmpty, "required") assert.Equal(t, []Error{{Location: "TextPtr", Message: "required"}}, r.validate(&sample{}), "nil pointer is absent") assert.Equal(t, []Error{{Location: "TextPtr", Message: "required", Value: ""}}, r.validate(&sample{TextPtr: ptr("")})) assert.Empty(t, r.validate(&sample{TextPtr: ptr("a")})) @@ -47,38 +47,38 @@ func TestDeref(t *testing.T) { func TestDerefOfNilNestedStruct(t *testing.T) { var r rules - NewValueField[*string](sampleField(t, "Inner.TextPtr"), pathHelper{}, sampleFields, r.add).As(Deref).Check(notEmpty, "required") + NewValueField[*string](sampleField(t, "Inner.TextPtr"), pathHelper{}, sampleFields, r.add, nil).As(Deref).Check(notEmpty, "required") assert.Empty(t, r.validate(&sample{})) } func TestRetype(t *testing.T) { var r rules - named := NewValueField[label](sampleField(t, "Label"), pathHelper{}, sampleFields, r.add) + named := NewValueField[label](sampleField(t, "Label"), pathHelper{}, sampleFields, r.add, nil) Retype[label, string](named).Check(func(v string) bool { return v == "ok" }, "bad") assert.Equal(t, []Error{{Location: "Label", Message: "bad", Value: "no"}}, r.validate(&sample{Label: "no"})) - text := NewValueField[string](sampleField(t, "Text"), pathHelper{}, sampleFields, r.add) + text := NewValueField[string](sampleField(t, "Text"), pathHelper{}, sampleFields, r.add, nil) assert.Same(t, text, Retype[string, string](text), "the same type isn't wrapped") assert.PanicsWithValue(t, "valigo: field Num has type int, string expected", func() { - Retype[int, string](NewValueField[int](sampleField(t, "Num"), pathHelper{}, sampleFields, r.add)) + Retype[int, string](NewValueField[int](sampleField(t, "Num"), pathHelper{}, sampleFields, r.add, nil)) }) } func TestRetypeSlice(t *testing.T) { var r rules - NewSliceFieldConfigurator[*string](sampleField(t, "TextPtrs"), pathHelper{}, sampleFields, r.add).As(toTypedSlice).Required().NotEmpty() + NewSliceFieldConfigurator[*string](sampleField(t, "TextPtrs"), pathHelper{}, sampleFields, r.add, nil).As(toTypedSlice).Required().NotEmpty() assert.Equal(t, []Error{ {Location: "TextPtrs[1]", Message: "required"}, {Location: "TextPtrs[2]", Message: "required", Value: ""}, }, r.validate(&sample{TextPtrs: []*string{ptr("a"), nil, ptr("")}})) - texts := NewSliceFieldConfigurator[string](sampleField(t, "Texts"), pathHelper{}, sampleFields, r.add) + texts := NewSliceFieldConfigurator[string](sampleField(t, "Texts"), pathHelper{}, sampleFields, r.add, nil) assert.Same(t, texts, RetypeSlice[string, string](texts), "the same type isn't wrapped") } func TestSlicePtr(t *testing.T) { var r rules - NewValueField[*[]string](sampleField(t, "TextsPtr"), pathHelper{}, sampleFields, r.add).As(SlicePtr).As(toTypedSlice).MaxLen(1).NotEmpty() + NewValueField[*[]string](sampleField(t, "TextsPtr"), pathHelper{}, sampleFields, r.add, nil).As(SlicePtr).As(toTypedSlice).MaxLen(1).NotEmpty() assert.Empty(t, r.validate(&sample{}), "nil pointer to slice is absent") assert.Equal(t, []Error{ {Location: "TextsPtr", Message: "validation:slice:Cannot contain more than 1 elements", Value: 2}, @@ -88,7 +88,7 @@ func TestSlicePtr(t *testing.T) { func TestSlicePtrAfterWhenPanics(t *testing.T) { var r rules - f := NewValueField[*[]string](sampleField(t, "TextsPtr"), pathHelper{}, sampleFields, r.add) + f := NewValueField[*[]string](sampleField(t, "TextsPtr"), pathHelper{}, sampleFields, r.add, nil) assert.PanicsWithValue(t, "valigo: SlicePtr of field TextsPtr must be called before When and other conversions", func() { SlicePtr(f.When(func(context.Context, *[]string) bool { return true })) }) @@ -117,7 +117,7 @@ func TestSliceRules(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { var r rules - tt.setup(NewSliceFieldConfigurator[string](sampleField(t, "Texts"), pathHelper{}, sampleFields, r.add).As(toTypedSlice)) + tt.setup(NewSliceFieldConfigurator[string](sampleField(t, "Texts"), pathHelper{}, sampleFields, r.add, nil).As(toTypedSlice)) assert.Equal(t, tt.want, r.validate(tt.obj)) }) } diff --git a/shared/field.go b/shared/field.go index d5b0d0b..68fa95a 100644 --- a/shared/field.go +++ b/shared/field.go @@ -29,13 +29,33 @@ type Field[T any] struct { // root registers validation functions of the struct field itself, nil for the fields derived by When, // conversions and for slice elements root func(fn ValidationFn) + // rootDescribe describes the constraints of the struct field itself for SlicePtr + rootDescribe Describe + schema constraints } // NewValueField creates a Field for the struct field of type T or *T, // named types with the same underlying layout are allowed. -// fields resolves the pointers to other fields of the model, add registers a validation function of the configured struct. -func NewValueField[T any](field fmap.Field, h Helper, fields Fields, add func(fn ValidationFn)) *Field[T] { - return &Field[T]{field: field, h: h, fields: fields, add: fieldSource(add, valueGetter[T](field)), root: add} +// fields resolves the pointers to other fields of the model, add registers a validation function of the configured struct, +// describe registers the constraints of its rules, it can be nil. +func NewValueField[T any](field fmap.Field, h Helper, fields Fields, add func(fn ValidationFn), describe Describe) *Field[T] { + return &Field[T]{field: field, h: h, fields: fields, add: fieldSource(add, valueGetter[T](field)), root: add, + rootDescribe: describe, schema: newConstraints(describe, field)} +} + +// newConstraints returns the constraints of the struct field, describe can be nil. +func newConstraints(describe Describe, field fmap.Field) constraints { + if describe == nil { + return constraints{} + } + return constraints{describe: describe, field: field, modified: new(bool)} +} + +// Schema describes the rules of the value by the keyword of JSON Schema with the value, e.g. Schema("maxLength", 64), +// see Constraint. The conversions call it for their rules that JSON Schema can express. +func (f *Field[T]) Schema(keyword string, value any) *Field[T] { + f.schema.add(keyword, value) + return f } // Check adds a rule that fails when ok returns false. Absent values are skipped. @@ -80,6 +100,9 @@ func (f *Field[T]) RequiredMsg(ok func(v T) bool, msg Msg) *Field[T] { // Modify adds a step that changes the value in place, e.g. trims a string. Absent values are skipped. func (f *Field[T]) Modify(fn func(v *T)) *Field[T] { + if f.schema.modified != nil { + *f.schema.modified = true + } f.add(func(_ context.Context, _ Helper, _ any, v *T, errs []Error) []Error { if v != nil { fn(v) diff --git a/shared/field_test.go b/shared/field_test.go index 4c366a6..4aa1ea8 100644 --- a/shared/field_test.go +++ b/shared/field_test.go @@ -217,7 +217,7 @@ func TestFieldRules(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { var r rules - tt.setup(NewValueField[string](sampleField(t, "TextPtr"), pathHelper{}, sampleFields, r.add)) + tt.setup(NewValueField[string](sampleField(t, "TextPtr"), pathHelper{}, sampleFields, r.add, nil)) assert.Equal(t, tt.want, r.validate(tt.obj)) }) } @@ -231,7 +231,7 @@ func customEcho(f *Field[string]) { func TestFieldRegistersOneValidationFn(t *testing.T) { var r rules - f := NewValueField[string](sampleField(t, "Text"), pathHelper{}, sampleFields, r.add) + f := NewValueField[string](sampleField(t, "Text"), pathHelper{}, sampleFields, r.add, nil) f.Check(func(string) bool { return true }, "a") f.When(func(context.Context, string) bool { return true }).Check(func(string) bool { return true }, "b") f.Modify(func(*string) {}) @@ -240,7 +240,7 @@ func TestFieldRegistersOneValidationFn(t *testing.T) { func TestModifySkipsAbsent(t *testing.T) { var r rules - NewValueField[string](sampleField(t, "TextPtr"), pathHelper{}, sampleFields, r.add).Modify(func(*string) { panic("must not be called") }) + NewValueField[string](sampleField(t, "TextPtr"), pathHelper{}, sampleFields, r.add, nil).Modify(func(*string) { panic("must not be called") }) assert.Empty(t, r.validate(&sample{})) } @@ -262,7 +262,7 @@ func TestCheckWith(t *testing.T) { { name: "fails with the location of the other field", setup: func(r *rules) { - NewValueField[string](sampleField(t, "Text"), pathHelper{}, sampleFields, r.add).CheckWith(&sampleModel.Label2, same, "Should be %s %s", "equal to") + NewValueField[string](sampleField(t, "Text"), pathHelper{}, sampleFields, r.add, nil).CheckWith(&sampleModel.Label2, same, "Should be %s %s", "equal to") }, obj: &sample{Text: "a", Label2: "b"}, want: []Error{{Location: "Text", Message: "Should be equal to Label2", Value: "a"}}, @@ -270,28 +270,28 @@ func TestCheckWith(t *testing.T) { { name: "passes", setup: func(r *rules) { - NewValueField[string](sampleField(t, "Text"), pathHelper{}, sampleFields, r.add).CheckWith(&sampleModel.Label2, same, "bad") + NewValueField[string](sampleField(t, "Text"), pathHelper{}, sampleFields, r.add, nil).CheckWith(&sampleModel.Label2, same, "bad") }, obj: &sample{Text: "a", Label2: "a"}, }, { name: "absent value is skipped", setup: func(r *rules) { - NewValueField[*string](sampleField(t, "TextPtr"), pathHelper{}, sampleFields, r.add).As(Deref).CheckWith(&sampleModel.Label2, same, "bad") + NewValueField[*string](sampleField(t, "TextPtr"), pathHelper{}, sampleFields, r.add, nil).As(Deref).CheckWith(&sampleModel.Label2, same, "bad") }, obj: &sample{Label2: "a"}, }, { name: "absent other value is skipped", setup: func(r *rules) { - NewValueField[string](sampleField(t, "Text"), pathHelper{}, sampleFields, r.add).CheckWith(&sampleModel.Inner.Text, same, "bad") + NewValueField[string](sampleField(t, "Text"), pathHelper{}, sampleFields, r.add, nil).CheckWith(&sampleModel.Inner.Text, same, "bad") }, obj: &sample{Text: "a"}, }, { name: "elements are compared with a field of the object", setup: func(r *rules) { - NewSliceFieldConfigurator[string](sampleField(t, "Texts"), pathHelper{}, sampleFields, r.add).Each(func(e *Field[string]) { + NewSliceFieldConfigurator[string](sampleField(t, "Texts"), pathHelper{}, sampleFields, r.add, nil).Each(func(e *Field[string]) { e.CheckWith(&sampleModel.Label2, func(v, o string) bool { return v != o }, "Cannot be %s") }) }, @@ -312,6 +312,6 @@ func TestCheckWithForeignPointerPanics(t *testing.T) { var r rules var foreign string assert.Panics(t, func() { - NewValueField[string](sampleField(t, "Text"), pathHelper{}, sampleFields, r.add).CheckWith(&foreign, func(string, string) bool { return true }, "bad") + NewValueField[string](sampleField(t, "Text"), pathHelper{}, sampleFields, r.add, nil).CheckWith(&foreign, func(string, string) bool { return true }, "bad") }) } diff --git a/shared/map.go b/shared/map.go index 755f6f4..7bb3305 100644 --- a/shared/map.go +++ b/shared/map.go @@ -23,12 +23,15 @@ type MapFieldConfigurator[K comparable, V any] struct { fields Fields get func(obj any) *map[K]V add func(fn ValidationFn) + schema constraints } // NewMapFieldConfigurator creates a MapFieldConfigurator for the field of type map[K]V, -// fields resolves the pointers to other fields of the model, add registers a validation function of the configured struct. -func NewMapFieldConfigurator[K comparable, V any](field fmap.Field, h Helper, fields Fields, add func(fn ValidationFn)) *MapFieldConfigurator[K, V] { - return &MapFieldConfigurator[K, V]{field: field, h: h, fields: fields, get: valueGetter[map[K]V](field), add: add} +// fields resolves the pointers to other fields of the model, add registers a validation function of the configured struct, +// describe registers the constraints of its rules, it can be nil. +func NewMapFieldConfigurator[K comparable, V any](field fmap.Field, h Helper, fields Fields, add func(fn ValidationFn), describe Describe) *MapFieldConfigurator[K, V] { + return &MapFieldConfigurator[K, V]{field: field, h: h, fields: fields, get: valueGetter[map[K]V](field), add: add, + schema: newConstraints(describe, field)} } // As converts the map configurator to a typed one by conv. @@ -49,18 +52,22 @@ func (m *MapFieldConfigurator[K, V]) check(ok func(n int) bool, msg Msg) { // MaxLen checks that the map contains no more than maxLen elements. Absent map is skipped. func (m *MapFieldConfigurator[K, V]) MaxLen(maxLen int) *MapFieldConfigurator[K, V] { + m.schema.add("maxProperties", maxLen) m.check(func(n int) bool { return n <= maxLen }, M("map.max_len", mapMaxLenLocaleKey, P("max", maxLen))) return m } // MinLen checks that the map contains at least minLen elements. Absent map is skipped. func (m *MapFieldConfigurator[K, V]) MinLen(minLen int) *MapFieldConfigurator[K, V] { + m.schema.add("minProperties", minLen) m.check(func(n int) bool { return n >= minLen }, M("map.min_len", mapMinLenLocaleKey, P("min", minLen))) return m } // Required checks that the map is present and not empty. func (m *MapFieldConfigurator[K, V]) Required() *MapFieldConfigurator[K, V] { + m.schema.add(KeywordRequired, true) + m.schema.add("minProperties", 1) field, get, msg := m.field, m.get, M("map.required", mapRequiredLocaleKey) m.add(func(ctx context.Context, h Helper, obj any, errs []Error) []Error { if v := get(obj); v != nil && len(*v) > 0 { @@ -108,7 +115,8 @@ func (m *MapFieldConfigurator[K, V]) When(whenFn func(ctx context.Context, value // EachKey configures rules applied to every key of the map, the location of an error is Labels[key]. func (m *MapFieldConfigurator[K, V]) EachKey(fn func(key *Field[K])) *MapFieldConfigurator[K, V] { - fn(&Field[K]{field: m.field, h: m.h, fields: m.fields, add: mapSource(m.add, m.get, func(k K, _ V) K { return k })}) + fn(&Field[K]{field: m.field, h: m.h, fields: m.fields, add: mapSource(m.add, m.get, func(k K, _ V) K { return k }), + schema: m.schema.child(PathPropertyNames)}) return m } @@ -116,7 +124,8 @@ func (m *MapFieldConfigurator[K, V]) EachKey(fn func(key *Field[K])) *MapFieldCo // The values of a map aren't addressable: Modify rules, e.g. Trim, change a copy that is checked by the next rules, // the map keeps the original value. func (m *MapFieldConfigurator[K, V]) EachValue(fn func(value *Field[V])) *MapFieldConfigurator[K, V] { - fn(&Field[V]{field: m.field, h: m.h, fields: m.fields, add: mapSource(m.add, m.get, func(_ K, v V) V { return v })}) + fn(&Field[V]{field: m.field, h: m.h, fields: m.fields, add: mapSource(m.add, m.get, func(_ K, v V) V { return v }), + schema: m.schema.child(PathAdditionalProperties)}) return m } diff --git a/shared/map_test.go b/shared/map_test.go index 2d36641..4ac8ba2 100644 --- a/shared/map_test.go +++ b/shared/map_test.go @@ -33,11 +33,11 @@ func mapsFields(fieldPtr any) fmap.Field { } func newLabels(r *rules) *MapFieldConfigurator[string, string] { - return NewMapFieldConfigurator[string, string](mapsFields(&mapsModel.Labels), pathHelper{}, mapsFields, r.add) + return NewMapFieldConfigurator[string, string](mapsFields(&mapsModel.Labels), pathHelper{}, mapsFields, r.add, nil) } func newCounts(r *rules) *MapFieldConfigurator[string, int] { - return NewMapFieldConfigurator[string, int](mapsFields(&mapsModel.Counts), pathHelper{}, mapsFields, r.add) + return NewMapFieldConfigurator[string, int](mapsFields(&mapsModel.Counts), pathHelper{}, mapsFields, r.add, nil) } func TestMapFieldConfigurator(t *testing.T) { @@ -76,7 +76,7 @@ func TestMapFieldConfigurator(t *testing.T) { }) }, &mapsSample{Labels: map[string]string{"a": "x"}}, []Error{{Location: "Labels[a]", Message: "sees the modified copy", Value: "changed"}}}, {"rules of absent map are skipped", func(r *rules) { - NewMapFieldConfigurator[string, bool](mapsFields(&mapsModel.Inner.Tags), pathHelper{}, mapsFields, r.add). + NewMapFieldConfigurator[string, bool](mapsFields(&mapsModel.Inner.Tags), pathHelper{}, mapsFields, r.add, nil). MaxLen(0).EachKey(func(k *Field[string]) { k.Check(func(string) bool { return false }, "bad") }) }, &mapsSample{}, nil}, {"custom", func(r *rules) { @@ -92,7 +92,7 @@ func TestMapFieldConfigurator(t *testing.T) { }) }, &mapsSample{Counts: map[string]int{"a": 6, "b": 6}}, []Error{{Location: "Counts", Message: "Sum is too big", Value: 12}}}, {"custom skips absent", func(r *rules) { - NewMapFieldConfigurator[string, bool](mapsFields(&mapsModel.Inner.Tags), pathHelper{}, mapsFields, r.add). + NewMapFieldConfigurator[string, bool](mapsFields(&mapsModel.Inner.Tags), pathHelper{}, mapsFields, r.add, nil). Custom(func(context.Context, *FieldCustomHelper, map[string]bool) []Error { panic("must not be called") }) }, &mapsSample{}, nil}, {"when false", func(r *rules) { diff --git a/shared/message_test.go b/shared/message_test.go index 5dc97ac..93eb5b2 100644 --- a/shared/message_test.go +++ b/shared/message_test.go @@ -34,7 +34,7 @@ func TestMessages(t *testing.T) { { name: "check by a key", setup: func(r *rules) { - NewValueField[string](sampleField(t, "Text"), pathHelper{}, sampleFields, r.add).Check(notEmpty, "required %s", "x") + NewValueField[string](sampleField(t, "Text"), pathHelper{}, sampleFields, r.add, nil).Check(notEmpty, "required %s", "x") }, obj: &sample{}, want: []Error{{Location: "Text", Message: "required x", Value: "", Code: "required %s"}}, @@ -42,7 +42,7 @@ func TestMessages(t *testing.T) { { name: "check by a message", setup: func(r *rules) { - NewValueField[string](sampleField(t, "Text"), pathHelper{}, sampleFields, r.add).CheckMsg(notEmpty, M("string.required", "required")) + NewValueField[string](sampleField(t, "Text"), pathHelper{}, sampleFields, r.add, nil).CheckMsg(notEmpty, M("string.required", "required")) }, obj: &sample{}, want: []Error{{Location: "Text", Message: "required", Value: "", Code: "string.required"}}, @@ -50,7 +50,7 @@ func TestMessages(t *testing.T) { { name: "required by a message", setup: func(r *rules) { - NewValueField[*string](sampleField(t, "TextPtr"), pathHelper{}, sampleFields, r.add).As(Deref).RequiredMsg(notEmpty, M("string.required", "required")) + NewValueField[*string](sampleField(t, "TextPtr"), pathHelper{}, sampleFields, r.add, nil).As(Deref).RequiredMsg(notEmpty, M("string.required", "required")) }, obj: &sample{}, want: []Error{{Location: "TextPtr", Message: "required", Code: "string.required"}}, @@ -58,7 +58,7 @@ func TestMessages(t *testing.T) { { name: "check with another field", setup: func(r *rules) { - NewValueField[string](sampleField(t, "Text"), pathHelper{}, sampleFields, r.add). + NewValueField[string](sampleField(t, "Text"), pathHelper{}, sampleFields, r.add, nil). CheckWithMsg(&sampleModel.Label2, func(v, o string) bool { return v == o }, M("string.equal_field", "equal to %s")) }, obj: &sample{Text: "a", Label2: "b"}, @@ -67,7 +67,7 @@ func TestMessages(t *testing.T) { { name: "slice length", setup: func(r *rules) { - NewSliceFieldConfigurator[string](sampleField(t, "Texts"), pathHelper{}, sampleFields, r.add).MinLen(2).MaxLen(0) + NewSliceFieldConfigurator[string](sampleField(t, "Texts"), pathHelper{}, sampleFields, r.add, nil).MinLen(2).MaxLen(0) }, obj: &sample{Texts: []string{"a"}}, want: []Error{ @@ -78,7 +78,7 @@ func TestMessages(t *testing.T) { { name: "slice required", setup: func(r *rules) { - NewSliceFieldConfigurator[string](sampleField(t, "Texts"), pathHelper{}, sampleFields, r.add).Required() + NewSliceFieldConfigurator[string](sampleField(t, "Texts"), pathHelper{}, sampleFields, r.add, nil).Required() }, obj: &sample{}, want: []Error{{Location: "Texts", Message: "validation:slice:Should be fulfilled", Code: "slice.required"}}, @@ -86,7 +86,7 @@ func TestMessages(t *testing.T) { { name: "custom of an element by a message", setup: func(r *rules) { - NewSliceFieldConfigurator[string](sampleField(t, "Texts"), pathHelper{}, sampleFields, r.add).Each(func(e *Field[string]) { + NewSliceFieldConfigurator[string](sampleField(t, "Texts"), pathHelper{}, sampleFields, r.add, nil).Each(func(e *Field[string]) { e.Custom(func(ctx context.Context, h *FieldCustomHelper, v string) []Error { return []Error{h.ErrorMsg(ctx, v, M("tag.reserved", "reserved %v", P("tag", v)))} }) diff --git a/shared/schema.go b/shared/schema.go new file mode 100644 index 0000000..7bc6360 --- /dev/null +++ b/shared/schema.go @@ -0,0 +1,74 @@ +package shared + +import ( + "reflect" + + "github.com/insei/fmap/v3" +) + +// The keywords of JSON Schema in Constraint.Path from the schema of a field to the schema of its parts. +const ( + // PathItems is the schema of the elements of a slice. + PathItems = "items" + // PathAdditionalProperties is the schema of the values of a map. + PathAdditionalProperties = "additionalProperties" + // PathPropertyNames is the schema of the keys of a map. + PathPropertyNames = "propertyNames" +) + +// KeywordRequired is the Keyword of the constraint of Required: the field is in the required properties of its object. +const KeywordRequired = "required" + +// Constraint is a rule of a field that JSON Schema can express, e.g. maxLength 64 of MaxRunes(64), +// for the generators of the schemas of the API. Only the unconditional rules are described: +// the rules under When are not; after a Modify rule, e.g. Trim, only Required is, the schema describes the raw value. +// The constraints describe the rules approximately: valigo stays the validation of the values. +type Constraint struct { + // Struct is the configured struct type. + Struct reflect.Type + // Field is the field of the rule, a field of Struct or of its nested structs. + Field fmap.Field + // Path is the keywords from the schema of the field to the schema of the constrained value: + // [items] for the elements of a slice, [additionalProperties] for the values of a map, [propertyNames] for its keys. + Path []string + // Keyword is the keyword of JSON Schema: maxLength, minimum, enum, pattern, format, required... + Keyword string + // Value is the value of the keyword. + Value any +} + +// Describe registers the constraints of a configured struct, it is nil for conditional rules. +type Describe func(c Constraint) + +// constraints describes the rules of one value, it is the zero value for the values without constraints. +type constraints struct { + describe Describe + field fmap.Field + path []string + // modified is true after a Modify rule, only Required is described then + modified *bool +} + +func (c constraints) add(keyword string, value any) { + if c.describe == nil || (c.modified != nil && *c.modified && keyword != KeywordRequired) { + return + } + c.describe(Constraint{Field: c.field, Path: c.path, Keyword: keyword, Value: value}) +} + +// child returns the constraints of the parts of the value by the keyword of the path, e.g. items. +func (c constraints) child(keyword string) constraints { + if c.describe == nil { + return constraints{} + } + return constraints{describe: c.describe, field: c.field, path: append(c.path[:len(c.path):len(c.path)], keyword), modified: new(bool)} +} + +// Values converts values to []any, e.g. for the enum keyword. +func Values[T any](values []T) []any { + result := make([]any, len(values)) + for i, v := range values { + result[i] = v + } + return result +} diff --git a/shared/schema_test.go b/shared/schema_test.go new file mode 100644 index 0000000..9409b5e --- /dev/null +++ b/shared/schema_test.go @@ -0,0 +1,60 @@ +package shared + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" +) + +// schema collects the constraints of the configurators. +type schema []Constraint + +func (s *schema) describe(c Constraint) { + *s = append(*s, c) +} + +func (s schema) keywords() []string { + result := make([]string, len(s)) + for i, c := range s { + result[i] = c.Field.GetStructPath() + " " + c.Keyword + for _, p := range c.Path { + result[i] += " " + p + } + } + return result +} + +func TestSchema(t *testing.T) { + var r rules + var s schema + f := NewValueField[string](sampleField(t, "Text"), pathHelper{}, sampleFields, r.add, s.describe) + f.Schema("maxLength", 3).As(Retype[string, string]).Schema("pattern", "^a") + f.When(func(context.Context, string) bool { return true }).Schema("minLength", 1) + f.Modify(func(*string) {}).Schema("maxLength", 2).Schema(KeywordRequired, true) + + NewValueField[*string](sampleField(t, "TextPtr"), pathHelper{}, sampleFields, r.add, s.describe).As(Deref).Schema("format", "email") + NewValueField[*[]string](sampleField(t, "TextsPtr"), pathHelper{}, sampleFields, r.add, s.describe).As(SlicePtr).MaxLen(2) + + texts := NewSliceFieldConfigurator[string](sampleField(t, "Texts"), pathHelper{}, sampleFields, r.add, s.describe) + texts.Schema("uniqueItems", true).Each(func(e *Field[string]) { + e.Modify(func(*string) {}).Schema("maxLength", 1) + }).EachField().Schema("minLength", 1) + texts.When(func(context.Context, Elems[string]) bool { return true }).MaxLen(1).EachField().Schema("maxLength", 1) + + assert.Equal(t, []string{ + "Text maxLength", "Text pattern", "Text required", + "TextPtr format", + "TextsPtr maxItems", + "Texts uniqueItems", "Texts minLength items", + }, s.keywords()) + + // without describe there is nothing to register + NewValueField[string](sampleField(t, "Text"), pathHelper{}, sampleFields, r.add, nil).Modify(func(*string) {}).Schema("maxLength", 1) + NewSliceFieldConfigurator[string](sampleField(t, "Texts"), pathHelper{}, sampleFields, r.add, nil).EachField().Schema("maxLength", 1) +} + +func TestValues(t *testing.T) { + assert.Equal(t, []any{1, 2}, Values([]int{1, 2})) + assert.Equal(t, []any{}, Values([]string{})) +} diff --git a/shared/slice.go b/shared/slice.go index ba77b07..349c8f1 100644 --- a/shared/slice.go +++ b/shared/slice.go @@ -119,13 +119,23 @@ type SliceFieldConfigurator[E any] struct { fields Fields get func(obj any) (Elems[E], bool) add func(fn ValidationFn) + schema constraints } // NewSliceFieldConfigurator creates a SliceFieldConfigurator for the field of type []E, *[]E, []*E or *[]*E, // named types with the same underlying layout are allowed. -// fields resolves the pointers to other fields of the model, add registers a validation function of the configured struct. -func NewSliceFieldConfigurator[E any](field fmap.Field, h Helper, fields Fields, add func(fn ValidationFn)) *SliceFieldConfigurator[E] { - return &SliceFieldConfigurator[E]{field: field, h: h, fields: fields, get: elemsGetter[E](field), add: add} +// fields resolves the pointers to other fields of the model, add registers a validation function of the configured struct, +// describe registers the constraints of its rules, it can be nil. +func NewSliceFieldConfigurator[E any](field fmap.Field, h Helper, fields Fields, add func(fn ValidationFn), describe Describe) *SliceFieldConfigurator[E] { + return &SliceFieldConfigurator[E]{field: field, h: h, fields: fields, get: elemsGetter[E](field), add: add, + schema: newConstraints(describe, field)} +} + +// Schema describes the rules of the slice by the keyword of JSON Schema with the value, e.g. Schema("uniqueItems", true), +// see Constraint. +func (s *SliceFieldConfigurator[E]) Schema(keyword string, value any) *SliceFieldConfigurator[E] { + s.schema.add(keyword, value) + return s } // Each configures rules applied to every element of the slice. @@ -136,7 +146,7 @@ func (s *SliceFieldConfigurator[E]) Each(fn func(elem *Field[E])) *SliceFieldCon // EachField returns a Field that applies rules to every element of the slice. func (s *SliceFieldConfigurator[E]) EachField() *Field[E] { - return &Field[E]{field: s.field, h: s.h, fields: s.fields, add: eachSource(s.add, s.get)} + return &Field[E]{field: s.field, h: s.h, fields: s.fields, add: eachSource(s.add, s.get), schema: s.schema.child(PathItems)} } func (s *SliceFieldConfigurator[E]) check(ok func(n int) bool, msg Msg) { @@ -152,18 +162,22 @@ func (s *SliceFieldConfigurator[E]) check(ok func(n int) bool, msg Msg) { // MaxLen checks that the slice contains no more than maxLen elements. Absent slice is skipped. func (s *SliceFieldConfigurator[E]) MaxLen(maxLen int) *SliceFieldConfigurator[E] { + s.schema.add("maxItems", maxLen) s.check(func(n int) bool { return n <= maxLen }, M("slice.max_len", sliceMaxLenLocaleKey, P("max", maxLen))) return s } // MinLen checks that the slice contains at least minLen elements. Absent slice is skipped. func (s *SliceFieldConfigurator[E]) MinLen(minLen int) *SliceFieldConfigurator[E] { + s.schema.add("minItems", minLen) s.check(func(n int) bool { return n >= minLen }, M("slice.min_len", sliceMinLenLocaleKey, P("min", minLen))) return s } // Required checks that the slice is present and not empty. func (s *SliceFieldConfigurator[E]) Required() *SliceFieldConfigurator[E] { + s.schema.add(KeywordRequired, true) + s.schema.add("minItems", 1) field, get, msg := s.field, s.get, M("slice.required", sliceRequiredLocaleKey) s.add(func(ctx context.Context, h Helper, obj any, errs []Error) []Error { if elems, _ := get(obj); elems.n > 0 { diff --git a/shared/slice_test.go b/shared/slice_test.go index 1293721..8a294d8 100644 --- a/shared/slice_test.go +++ b/shared/slice_test.go @@ -193,7 +193,7 @@ func TestSliceFieldConfigurator(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { var r rules - tt.setup(NewSliceFieldConfigurator[string](sampleField(t, tt.path), pathHelper{}, sampleFields, r.add)) + tt.setup(NewSliceFieldConfigurator[string](sampleField(t, tt.path), pathHelper{}, sampleFields, r.add, nil)) assert.Equal(t, tt.want, r.validate(tt.obj)) }) } @@ -201,7 +201,7 @@ func TestSliceFieldConfigurator(t *testing.T) { func TestEachRegistersOneValidationFn(t *testing.T) { var r rules - NewSliceFieldConfigurator[string](sampleField(t, "Texts"), pathHelper{}, sampleFields, r.add).Each(func(e *Field[string]) { + NewSliceFieldConfigurator[string](sampleField(t, "Texts"), pathHelper{}, sampleFields, r.add, nil).Each(func(e *Field[string]) { e.Check(func(string) bool { return true }, "a") e.Check(func(string) bool { return true }, "b") }) diff --git a/str/base.go b/str/base.go index 8368b66..97a74e0 100644 --- a/str/base.go +++ b/str/base.go @@ -5,6 +5,7 @@ import ( "regexp" "slices" "strings" + "time" "unicode/utf8" "github.com/insei/valigo/shared" @@ -48,6 +49,9 @@ const ( var emailRegexp = regexp.MustCompile(`^[^\s,@#$%^&*!()]+@([a-zA-Z0-9]+[.])+[a-zA-Z]{2,8}$`) +// datetimeFormats are the formats of JSON Schema of the layouts of Datetime. +var datetimeFormats = map[string]string{time.RFC3339: "date-time", time.RFC3339Nano: "date-time", time.DateOnly: "date"} + // BaseConfigurator configures rules for a string value. type BaseConfigurator struct { f *shared.Field[string] @@ -77,6 +81,7 @@ func (i *BaseConfigurator) Trim() *BaseConfigurator { // MaxLen checks if the string length is not greater than the given maximum length. func (i *BaseConfigurator) MaxLen(maxLen int) *BaseConfigurator { + i.f.Schema("maxLength", maxLen) // the bytes are not less than the characters, the schema is not stricter i.f.CheckMsg(func(v string) bool { return len(v) <= maxLen }, shared.M("string.max_len", maxLengthLocaleKey, shared.P("max", maxLen))) return i } @@ -89,18 +94,21 @@ func (i *BaseConfigurator) MinLen(minLen int) *BaseConfigurator { // MinRunes checks if the string has at least minLen characters, unlike MinLen it counts runes, not bytes. func (i *BaseConfigurator) MinRunes(minLen int) *BaseConfigurator { + i.f.Schema("minLength", minLen) i.f.CheckMsg(func(v string) bool { return utf8.RuneCountInString(v) >= minLen }, shared.M("string.min_runes", minLengthLocaleKey, shared.P("min", minLen))) return i } // MaxRunes checks if the string has no more than maxLen characters, unlike MaxLen it counts runes, not bytes. func (i *BaseConfigurator) MaxRunes(maxLen int) *BaseConfigurator { + i.f.Schema("maxLength", maxLen) i.f.CheckMsg(func(v string) bool { return utf8.RuneCountInString(v) <= maxLen }, shared.M("string.max_runes", maxLengthLocaleKey, shared.P("max", maxLen))) return i } // Required checks if the string is present and not empty. func (i *BaseConfigurator) Required() *BaseConfigurator { + i.f.Schema(shared.KeywordRequired, true).Schema("minLength", 1) i.f.RequiredMsg(func(v string) bool { return len(v) > 0 }, shared.M("string.required", requiredLocaleKey)) return i } @@ -113,6 +121,7 @@ func (i *BaseConfigurator) Custom(f func(ctx context.Context, h *shared.FieldCus // Regexp checks if the string value matches the given regular expression. func (i *BaseConfigurator) Regexp(regexp *regexp.Regexp, opts ...RegexpOption) *BaseConfigurator { + i.f.Schema("pattern", regexp.String()) options := regexpOptions{ localeKey: regexpLocaleKey, } @@ -125,12 +134,14 @@ func (i *BaseConfigurator) Regexp(regexp *regexp.Regexp, opts ...RegexpOption) * // AnyOf checks if the string value is one of the allowed values. func (i *BaseConfigurator) AnyOf(allowed ...string) *BaseConfigurator { + i.f.Schema("enum", shared.Values(allowed)) i.f.CheckMsg(func(v string) bool { return slices.Contains(allowed, v) }, shared.M("string.any_of", anyOfLocaleKey, shared.P("values", allowed))) return i } // Email checks if the string value is an email address. func (i *BaseConfigurator) Email() *BaseConfigurator { + i.f.Schema("format", "email") i.f.CheckMsg(emailRegexp.MatchString, shared.M("string.email", emailLocaleKey)) return i } @@ -138,6 +149,7 @@ func (i *BaseConfigurator) Email() *BaseConfigurator { // URL checks if the string is an absolute URL with a scheme and a host: https://example.com/path?q=1. // The host is a hostname, an IPv4 address or an IPv6 address in brackets. func (i *BaseConfigurator) URL() *BaseConfigurator { + i.f.Schema("format", "uri") i.f.CheckMsg(isURL, shared.M("string.url", urlLocaleKey)) return i } @@ -150,30 +162,35 @@ func (i *BaseConfigurator) IP() *BaseConfigurator { // IPv4 checks if the string is an IPv4 address. func (i *BaseConfigurator) IPv4() *BaseConfigurator { + i.f.Schema("format", "ipv4") i.f.CheckMsg(isIPv4, shared.M("string.ipv4", ipv4LocaleKey)) return i } // IPv6 checks if the string is an IPv6 address. func (i *BaseConfigurator) IPv6() *BaseConfigurator { + i.f.Schema("format", "ipv6") i.f.CheckMsg(isIPv6, shared.M("string.ipv6", ipv6LocaleKey)) return i } // Hostname checks if the string is a hostname by RFC 1123: example.com, localhost, 1.example. func (i *BaseConfigurator) Hostname() *BaseConfigurator { + i.f.Schema("format", "hostname") i.f.CheckMsg(isHostname, shared.M("string.hostname", hostnameLocaleKey)) return i } // UUID checks if the string is a UUID in the canonical form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, any case. func (i *BaseConfigurator) UUID() *BaseConfigurator { + i.f.Schema("format", "uuid") i.f.CheckMsg(isUUID, shared.M("string.uuid", uuidLocaleKey)) return i } // Alphanumeric checks if the string is not empty and has only ASCII letters and digits. func (i *BaseConfigurator) Alphanumeric() *BaseConfigurator { + i.f.Schema("pattern", "^[a-zA-Z0-9]+$") i.f.CheckMsg(isAlphanumeric, shared.M("string.alphanumeric", alnumLocaleKey)) return i } @@ -187,30 +204,35 @@ func (i *BaseConfigurator) EqualField(other *string) *BaseConfigurator { // Prefix checks if the string starts with prefix. func (i *BaseConfigurator) Prefix(prefix string) *BaseConfigurator { + i.f.Schema("pattern", "^"+regexp.QuoteMeta(prefix)) i.f.CheckMsg(func(v string) bool { return strings.HasPrefix(v, prefix) }, shared.M("string.prefix", prefixLocaleKey, shared.P("prefix", prefix))) return i } // Suffix checks if the string ends with suffix. func (i *BaseConfigurator) Suffix(suffix string) *BaseConfigurator { + i.f.Schema("pattern", regexp.QuoteMeta(suffix)+"$") i.f.CheckMsg(func(v string) bool { return strings.HasSuffix(v, suffix) }, shared.M("string.suffix", suffixLocaleKey, shared.P("suffix", suffix))) return i } // Contains checks if the string contains substr. func (i *BaseConfigurator) Contains(substr string) *BaseConfigurator { + i.f.Schema("pattern", regexp.QuoteMeta(substr)) i.f.CheckMsg(func(v string) bool { return strings.Contains(v, substr) }, shared.M("string.contains", containsLocaleKey, shared.P("substring", substr))) return i } // Base64 checks if the string is base64 of RFC 4648 with padding, the standard alphabet. func (i *BaseConfigurator) Base64() *BaseConfigurator { + i.f.Schema("contentEncoding", "base64") i.f.CheckMsg(isBase64, shared.M("string.base64", base64LocaleKey)) return i } // Base64URL checks if the string is base64 of RFC 4648 with the URL and filename safe alphabet, padding is optional. func (i *BaseConfigurator) Base64URL() *BaseConfigurator { + i.f.Schema("contentEncoding", "base64url") i.f.CheckMsg(isBase64URL, shared.M("string.base64url", base64URLLocaleKey)) return i } @@ -223,6 +245,7 @@ func (i *BaseConfigurator) JSON() *BaseConfigurator { // Semver checks if the string is a semantic version of semver.org without the "v" prefix: 1.2.3-rc.1+build.5. func (i *BaseConfigurator) Semver() *BaseConfigurator { + i.f.Schema("pattern", semverRegexp.String()) i.f.CheckMsg(semverRegexp.MatchString, shared.M("string.semver", semverLocaleKey)) return i } @@ -241,12 +264,14 @@ func (i *BaseConfigurator) MAC() *BaseConfigurator { // E164 checks if the string is a phone number of E.164: +14155550123. func (i *BaseConfigurator) E164() *BaseConfigurator { + i.f.Schema("pattern", `^\+[1-9][0-9]{1,14}$`) i.f.CheckMsg(isE164, shared.M("string.e164", e164LocaleKey)) return i } // HexColor checks if the string is a hex color: #rgb, #rgba, #rrggbb or #rrggbbaa. func (i *BaseConfigurator) HexColor() *BaseConfigurator { + i.f.Schema("pattern", `^#([0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$`) i.f.CheckMsg(isHexColor, shared.M("string.hex_color", hexColorLocaleKey)) return i } @@ -271,6 +296,9 @@ func (i *BaseConfigurator) Uppercase() *BaseConfigurator { // Datetime checks if the string is a date or a time of the layout of time.Parse: Datetime(time.DateOnly). func (i *BaseConfigurator) Datetime(layout string) *BaseConfigurator { + if format, ok := datetimeFormats[layout]; ok { + i.f.Schema("format", format) + } i.f.CheckMsg(isDatetime(layout), shared.M("string.datetime", datetimeLocaleKey, shared.P("layout", layout))) return i } diff --git a/uuid/base.go b/uuid/base.go index befd730..e11dc22 100644 --- a/uuid/base.go +++ b/uuid/base.go @@ -35,12 +35,14 @@ func Of[U uuid.UUID | *uuid.UUID](f *shared.Field[U]) *BaseConfigurator { // Required checks if the uuid is present and not uuid.Nil. func (i *BaseConfigurator) Required() *BaseConfigurator { + i.f.Schema(shared.KeywordRequired, true) i.f.RequiredMsg(func(v uuid.UUID) bool { return v != uuid.Nil }, shared.M("uuid.required", requiredLocaleKey)) return i } // AnyOf checks if the uuid value is one of the allowed values. func (i *BaseConfigurator) AnyOf(allowed ...uuid.UUID) *BaseConfigurator { + i.f.Schema("enum", shared.Values(allowed)) i.f.CheckMsg(func(v uuid.UUID) bool { return slices.Contains(allowed, v) }, shared.M("uuid.any_of", anyOfLocaleKey, shared.P("values", allowed))) return i } diff --git a/validator.go b/validator.go index 33b016b..84b1be4 100644 --- a/validator.go +++ b/validator.go @@ -1,7 +1,9 @@ package valigo import ( + "cmp" "context" + "maps" "reflect" "slices" "sync" @@ -15,6 +17,7 @@ import ( // Validator holds validation rules of the configured types. type Validator struct { validators map[reflect.Type][]shared.ValidationFn + constraints map[reflect.Type][]shared.Constraint helper *helper transformError func(errs []shared.Error) []error } @@ -79,6 +82,18 @@ func dataPtr(v any) unsafe.Pointer { return (*[2]unsafe.Pointer)(unsafe.Pointer(&v))[1] } +// Constraints returns the rules of the configured structs that JSON Schema can express, see shared.Constraint, +// for the generators of the schemas of the API. The structs are sorted by their names, the rules are in the order +// of the configuration. +func (v *Validator) Constraints() []shared.Constraint { + types := slices.SortedFunc(maps.Keys(v.constraints), func(a, b reflect.Type) int { return cmp.Compare(a.String(), b.String()) }) + var result []shared.Constraint + for _, t := range types { + result = append(result, v.constraints[t]...) + } + return result +} + // GetHelper returns the helper object associated with the Validator instance. func (v *Validator) GetHelper() shared.Helper { return v.helper @@ -88,8 +103,9 @@ func (v *Validator) GetHelper() shared.Helper { // It also applies any options passed to the function to the new instance. func New(opts ...Option) *Validator { v := &Validator{ - validators: make(map[reflect.Type][]shared.ValidationFn), - helper: newHelper(), + validators: make(map[reflect.Type][]shared.ValidationFn), + constraints: make(map[reflect.Type][]shared.Constraint), + helper: newHelper(), transformError: func(errs []shared.Error) []error { errsNew := make([]error, len(errs)) for i, err := range errs { @@ -110,6 +126,7 @@ func New(opts ...Option) *Validator { // call it on application start and not concurrently with Validate. func Configure[T any](v *Validator, fn func(builder Configurator[T], m *T)) { delete(v.validators, reflect.TypeFor[*T]()) + delete(v.constraints, reflect.TypeFor[T]()) model := new(T) fields, err := fmap.GetFrom(model) if err != nil {