-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstruct.go
More file actions
170 lines (140 loc) · 3.85 KB
/
Copy pathstruct.go
File metadata and controls
170 lines (140 loc) · 3.85 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
package ecto
import (
"cmp"
"encoding/json"
"reflect"
"strings"
"github.com/egsam98/errors"
"github.com/samber/lo"
)
var _ Schema = (*StructSchema[any])(nil)
var _ IStructSchema = (*StructSchema[any])(nil)
// StructSchema represents schema for struct types via hashmap as a struct field to its schema
type StructSchema[T any] struct {
fields M
meta map[string]FieldMeta
}
type FieldMeta struct {
Index int
Tag string
}
type M = map[string]Schema
func Struct[T any](fields M) StructSchema[T] {
typ := reflect.TypeFor[T]()
if typ.Kind() != reflect.Struct {
panic(errors.Errorf("%s: not a struct", typ))
}
self := StructSchema[T]{fields: fields}
self.makeMeta()
return self
}
// Process may return MapError
func (s StructSchema[T]) Process(ptr *T) error { return s.process(ptr) }
// Cast deserializes bytes into type and runs Process.
func (s StructSchema[T]) Cast(src []byte, deserialize func([]byte, any) error, opts ...CastOpt) (T, error) {
var data T
if err := deserialize(src, &data); err != nil {
return data, errors.Wrapf(err, "deserialize %s into %T", src, data)
}
applyCastOpts(&data, opts...)
return data, s.Process(&data)
}
type Decoder interface {
Decode(any) error
}
// Decode decoding into T from external Decoder and runs Process
func (s StructSchema[T]) Decode(dec Decoder, opts ...CastOpt) (T, error) {
var data T
if err := dec.Decode(&data); err != nil {
return data, errors.Wrapf(err, "decode into %T", data)
}
applyCastOpts(&data, opts...)
return data, s.Process(&data)
}
// CastJSON is shorthand for Cast with json.Unmarshal deserializer
func (s StructSchema[T]) CastJSON(src []byte, opts ...CastOpt) (T, error) {
return s.Cast(src, json.Unmarshal, opts...)
}
func (s StructSchema[T]) CastToAny(src []byte, deserialize func([]byte, any) error, opts ...CastOpt) (any, error) {
return s.Cast(src, deserialize, opts...)
}
// Extend existing schema
func (s StructSchema[T]) Extend(fields M) StructSchema[T] {
return Struct[T](lo.Assign(s.fields, fields))
}
func (s StructSchema[T]) ForType() reflect.Type { return reflect.TypeFor[T]() }
func (s StructSchema[T]) process(ptrStruct any) error {
if len(s.fields) == 0 {
return nil
}
rv := reflect.ValueOf(ptrStruct).Elem()
var errs MapError
for key, schema := range s.fields {
keyMeta, ok := s.meta[key]
if !ok {
s.panicMissingKey(key)
}
ptr := rv.Field(keyMeta.Index).Addr().Interface()
if err := schema.process(ptr); err != nil {
errs.Add(keyMeta.Tag, err)
}
}
if len(errs) > 0 {
return errs
}
return nil
}
func (s StructSchema[T]) Fields() M { return s.fields }
// WithFields overwrites existing schema fields
func (s StructSchema[T]) WithFields(fields M) IStructSchema {
s.fields = fields
s.makeMeta()
return s
}
func (s StructSchema[T]) Meta() map[string]FieldMeta { return s.meta }
func (s *StructSchema[T]) makeMeta() {
s.meta = make(map[string]FieldMeta)
if len(s.fields) == 0 {
return
}
typ := reflect.TypeFor[T]()
for i := range typ.NumField() {
field := typ.Field(i)
tag, _, _ := strings.Cut(field.Tag.Get("json"), ",")
s.meta[field.Name] = FieldMeta{
Index: i,
Tag: cmp.Or(tag, field.Name),
}
}
for key, schema := range s.fields {
field, ok := typ.FieldByName(key)
if !ok {
s.panicMissingKey(key)
}
if err := validateSchema(field.Type, schema); err != nil {
panic(errors.Wrapf(err, "%T: %s", s, key))
}
}
}
func (s StructSchema[T]) panicMissingKey(key string) {
panic(errors.Errorf("%T: Missing struct schema key: %s", s, key))
}
type CastOpt func(*castConfig)
// Scrub replaces empty strings with nil for every `*string` type
func Scrub() CastOpt {
return func(cfg *castConfig) { cfg.scrub = true }
}
type castConfig struct {
scrub bool
}
func applyCastOpts[T any](data *T, opts ...CastOpt) {
var cfg castConfig
for _, opt := range opts {
if opt != nil {
opt(&cfg)
}
}
if cfg.scrub {
ScrubAny(data)
}
}