forked from labstack/echo
/
model.go
483 lines (423 loc) · 10.8 KB
/
model.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
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
// Copyright 2019 Adverax. All Rights Reserved.
// This file is part of project
//
// http://github.com/adverax/echo
//
// Licensed under the MIT (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://github.com/adverax/echo/blob/master/LICENSE
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package echo
import (
"encoding/json"
"encoding/xml"
"fmt"
"github.com/adverax/echo/generic"
"net/http"
"reflect"
"strings"
)
/*
Example:
func myLoginHandler(ctx echo.Context) error {
username := XXX{} // Create field
password := XXX{} // Create field
model := echo.Model{username, password}
rec := struct{
Username string
Password string
}{
Username: "Default name",
Password: "Default password,
}
if err := model.Resolve(ctx, &rec, &rec, nil); err != nil {
if err != echo.ErrModelSealed {
return err
}
// Record is valid
...
return ctx.Redirect(http.StatusSeeOther, "...")
}
// Show form
...
return nil
*/
// Mapper is abstract converter external field names into internal model field names.
type Mapper interface {
// Convert external representation to internal representation
Execute(name string) (string, bool)
}
type MapperFunc func(name string) (string, bool)
func (fn MapperFunc) Execute(name string) (string, bool) {
return fn(name)
}
type ListMapper []string
func (mapper ListMapper) Execute(name string) (string, bool) {
name = strings.Title(name)
for _, val := range mapper {
if val == name {
return name, true
}
}
return "", false
}
type DictMapper map[string]string
func (mapper DictMapper) Execute(name string) (string, bool) {
res, ok := mapper[name]
return res, ok
}
// Abstract field. Implemented by descendants of field.
type ModelField interface {
// Field has no errors
IsValid() bool
// Get list of validation errors
GetErrors() ValidationErrors
// Get name of field
GetName() string
// Get internal representation of value
GetVal() interface{}
// Set internal representation of value
SetVal(ctx Context, value interface{})
// Get external representation of value
GetValue() []string
// Set external representation of value
SetValue(ctx Context, value []string) error
// Validate field and extends field errors
Validate(ctx Context) error
// Get internal data as signed value
GetInt() int
// Get internal data as signed value
GetInt8() int8
// Get internal data as signed value
GetInt16() int16
// Get internal data as signed value
GetInt32() int32
// Get internal data as signed value
GetInt64() int64
// Get internal data as unsigned value
GetUint() uint
// Get internal data as unsigned value
GetUint8() uint8
// Get internal data as unsigned value
GetUint16() uint16
// Get internal data as unsigned value
GetUint32() uint32
// Get internal data as unsigned value
GetUint64() uint64
// Get internal data as decimal value
GetFloat32() float32
// Get internal data as decimal value
GetFloat64() float64
// Get internal data as string value
GetString() string
// Get internal data as boolean value
GetBoolean() bool
// Get flag disabled
GetDisabled() bool
// Get flag hidden
GetHidden() bool
// Delete all errors and uncheck field and set default value
Reset(ctx Context) error
}
type ValidatorFunc func() error
type Model map[string]interface{}
func (model Model) Clone() Model {
res := make(Model, 2*len(model))
for key, val := range model {
res[key] = val
}
return res
}
// Import and validate data
// Returns ErrModelSealed if model imported and validated.
func (model Model) Resolve(
ctx Context,
src interface{}, // Data source
dst interface{}, // Data destination
mapper Mapper, // Optional mapper
) error {
if src != nil {
err := model.Import(ctx, src, mapper)
if err != nil {
return err
}
}
if ctx.Request().Method != POST {
return nil
}
err := model.Bind(ctx)
if err != nil {
return err
}
if model.IsValid() {
if dst != nil {
err := model.Export(ctx, dst, mapper)
if err != nil {
return err
}
}
return ErrModelSealed
}
return nil
}
// Bind works with not structured data only.
func (model Model) Bind(
ctx Context,
) error {
req := ctx.Request()
if req.ContentLength == 0 {
if req.Method == http.MethodGet || req.Method == http.MethodDelete {
if err := model.BindFrom(ctx, ctx.QueryParams()); err != nil {
return NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err)
}
return nil
}
return NewHTTPError(http.StatusBadRequest, "Request body can't be empty")
}
var params map[string][]string
ctype := req.Header.Get(HeaderContentType)
switch {
case strings.HasPrefix(ctype, MIMEApplicationJSON):
var raw map[string]string
if err := json.NewDecoder(req.Body).Decode(raw); err != nil {
if ute, ok := err.(*json.UnmarshalTypeError); ok {
return NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Unmarshal type error: expected=%v, got=%v, field=%v, offset=%v", ute.Type, ute.Value, ute.Field, ute.Offset)).SetInternal(err)
} else if se, ok := err.(*json.SyntaxError); ok {
return NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Syntax error: offset=%v, error=%v", se.Offset, se.Error())).SetInternal(err)
}
return NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err)
}
params = MakeModelParams(raw)
case strings.HasPrefix(ctype, MIMEApplicationXML), strings.HasPrefix(ctype, MIMETextXML):
var raw map[string]string
if err := xml.NewDecoder(req.Body).Decode(raw); err != nil {
if ute, ok := err.(*xml.UnsupportedTypeError); ok {
return NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Unsupported type error: type=%v, error=%v", ute.Type, ute.Error())).SetInternal(err)
} else if se, ok := err.(*xml.SyntaxError); ok {
return NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Syntax error: line=%v, error=%v", se.Line, se.Error())).SetInternal(err)
}
return NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err)
}
case strings.HasPrefix(ctype, MIMEApplicationForm), strings.HasPrefix(ctype, MIMEMultipartForm):
var err error
params, err = ctx.FormParams()
if err != nil {
return NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err)
}
default:
return ErrUnsupportedMediaType
}
if err := model.BindFrom(ctx, params); err != nil {
return NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err)
}
return nil
}
func (model Model) BindFrom(
ctx Context,
data map[string][]string,
) error {
// Bind model
for _, item := range model {
if field, ok := item.(ModelField); ok {
err := field.Reset(ctx)
if err != nil {
return err
}
if field.GetDisabled() || field.GetHidden() {
continue
}
name := field.GetName()
value, ok := data[name]
if ok && len(value) != 0 {
err := field.SetValue(ctx, value)
if err != nil {
return err
}
}
err = field.Validate(ctx)
if err != nil {
return err
}
}
}
// Validate model
for _, item := range model {
if validator, ok := item.(ValidatorFunc); ok {
err := validator()
if err != nil {
return err
}
}
}
return nil
}
func (model Model) IsValid() bool {
for _, item := range model {
if field, ok := item.(ModelField); ok {
if field == nil {
continue
}
if !field.IsValid() {
return false
}
}
}
return true
}
// Import imports model data from external structure.
// External field names can be composite structure.
// For such fields need mapper, that defien dotted path to the target field.
func (model Model) Import(
ctx Context,
src interface{},
mapper Mapper,
) error {
if mapper == nil {
mapper = DefaultMapper
}
rec := reflect.ValueOf(src)
if rec.Kind() == reflect.Ptr {
rec = rec.Elem()
}
if rec.Kind() != reflect.Struct {
return fmt.Errorf("model.import: invalid type of source")
}
for _, item := range model {
if field, ok := item.(ModelField); ok {
if field == nil {
continue
}
if name, ok := mapper.Execute(field.GetName()); ok {
f := access(rec, name)
if f.Kind() != reflect.Invalid {
if f.CanInterface() {
field.SetVal(ctx, f.Interface())
}
}
}
}
}
return nil
}
// Export exports model data into external structure.
// External field names can be composite structure.
// For such fields need mapper, that defien dotted path to the target field.
func (model Model) Export(
ctx Context,
dst interface{},
mapper Mapper,
) error {
if mapper == nil {
mapper = DefaultMapper
}
rec := reflect.ValueOf(dst).Elem()
if rec.Kind() != reflect.Struct {
return fmt.Errorf("model.Export: invalid type of destination")
}
for _, item := range model {
if field, ok := item.(ModelField); ok {
if field == nil {
continue
}
if name, ok := mapper.Execute(field.GetName()); ok {
f := access(rec, name)
if f.Kind() != reflect.Invalid {
if f.CanSet() {
dst := f.Addr().Interface()
_ = generic.ConvertAssign(dst, field.GetVal())
}
}
}
}
}
return nil
}
func (model Model) Render(
ctx Context,
) (interface{}, error) {
res := make(map[string]interface{}, len(model)+1)
for key, item := range model {
if item == nil {
continue
}
f, err := RenderWidget(ctx, item)
if err != nil {
return nil, err
}
res[key] = f
}
return res, nil
}
type Models []Model
func (models Models) Bind(
ctx Context,
) error {
for _, model := range models {
err := model.Bind(ctx)
if err != nil {
return err
}
}
return nil
}
func (models Models) IsValid() bool {
for _, model := range models {
if model != nil && model.IsValid() {
return true
}
}
return false
}
func (models Models) Render(
ctx Context,
) (interface{}, error) {
res := make([]interface{}, 0, len(models))
for _, model := range models {
if model != nil {
item, err := model.Render(ctx)
if err != nil {
return nil, err
}
if item != nil {
res = append(res, item)
}
}
}
if len(res) == 0 {
return nil, nil
}
return res, nil
}
// Create name of field of band
func MakeMultiModelName(key, name string) string {
return fmt.Sprintf("[%s].%s", key, name)
}
// Create model parameters from map.
func MakeModelParams(raw map[string]string) map[string][]string {
params := make(map[string][]string, len(raw))
for k, v := range raw {
params[k] = []string{v}
}
return params
}
// Access to field
func access(rec reflect.Value, name string) reflect.Value {
if !strings.Contains(name, ".") {
return rec.FieldByName(name)
}
path := strings.Split(name, ".")
for _, item := range path {
rec = rec.FieldByName(item)
if rec.Kind() != reflect.Struct {
return rec
}
}
return rec
}