Test Failed
Push — main ( 05cfc8...747a0a )
by Igor
02:24
created

validation.go   A

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
cc 4
eloc 16
dl 0
loc 52
ccs 6
cts 6
cp 1
crap 4
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validation.ValidatableFunc.Validate 0 2 1
A validation.Filter 0 11 3
1
// Copyright 2021 Igor Lazarev. All rights reserved.
2
// Use of this source code is governed by a MIT-style
3
// license that can be found in the LICENSE file.
4
5
// Package validation provides tools for data validation.
6
// It is designed to create complex validation rules with abilities to hook into the validation process.
7
package validation
8
9
import (
10
	"context"
11
)
12
13
const DefaultGroup = "default"
14
15
// Validatable is interface for creating validatable types on the client side.
16
// By using it you can build complex validation rules on a set of objects used in other objects.
17
//
18
// Example
19
//  type Book struct {
20
//      Title    string
21
//      Author   string
22
//      Keywords []string
23
//  }
24
//
25
//  func (b Book) Validate(ctx context.Context, validator *validation.Validator) error {
26
//      return validator.Validate(
27
//          ctx,
28
//          validation.StringProperty("title", &b.Title, it.IsNotBlank()),
29
//          validation.StringProperty("author", &b.Author, it.IsNotBlank()),
30
//          validation.CountableProperty("keywords", len(b.Keywords), it.HasCountBetween(1, 10)),
31
//          validation.EachStringProperty("keywords", b.Keywords, it.IsNotBlank()),
32
//      )
33
//  }
34
type Validatable interface {
35
	Validate(ctx context.Context, validator *Validator) error
36
}
37
38
// ValidatableFunc is a functional adapter for the Validatable interface.
39
type ValidatableFunc func(ctx context.Context, validator *Validator) error
40
41
// Validate runs validation process on function.
42
func (f ValidatableFunc) Validate(ctx context.Context, validator *Validator) error {
43 1
	return f(ctx, validator)
44
}
45 1
46 1
// Filter is used for processing the list of errors to return a single ViolationList.
47 1
// If there is at least one non-violation error it will return it instead.
48 1
func Filter(violations ...error) error {
49
	list := &ViolationList{}
50
51
	for _, violation := range violations {
52 1
		err := list.AppendFromError(violation)
53
		if err != nil {
54
			return err
55
		}
56
	}
57
58
	return list.AsError()
59
}
60