forked from openflagr/flagr
/
variant.go
52 lines (45 loc) · 1.12 KB
/
variant.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package entity
import (
"database/sql/driver"
"encoding/json"
"fmt"
"github.com/paubox/paubox-flagr/pkg/util"
"github.com/spf13/cast"
"gorm.io/gorm"
)
// Variant is the struct that represent the experience/variant of the evaluation entity
type Variant struct {
gorm.Model
FlagID uint `gorm:"index:idx_variant_flagid"`
Key string
Attachment Attachment `gorm:"type:text"`
}
// Validate validates the Variant
func (v *Variant) Validate() error {
ok, msg := util.IsSafeKey(v.Key)
if !ok {
return fmt.Errorf(msg)
}
return nil
}
// Attachment supports dynamic configuration in variant
type Attachment map[string]interface{}
// Scan implements scanner interface
func (a *Attachment) Scan(value interface{}) error {
if value == nil {
return nil
}
s := cast.ToString(value)
if err := json.Unmarshal([]byte(s), a); err != nil {
return fmt.Errorf("cannot scan %v into Attachment type. err: %v", value, err)
}
return nil
}
// Value implements valuer interface
func (a Attachment) Value() (driver.Value, error) {
bytes, err := json.Marshal(a)
if err != nil {
return nil, err
}
return string(bytes), nil
}