-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecoder.go
More file actions
59 lines (48 loc) · 1.03 KB
/
decoder.go
File metadata and controls
59 lines (48 loc) · 1.03 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
package mongodata
type Decoder[M any] interface {
Schema() string
Decode(Document) (*M, error)
}
type Document interface {
Decode(any) error
}
func Decode[M any](decoder Document) (*M, error) {
var m M
return &m, decoder.Decode(&m)
}
func DecodeModel[M any](decoder Document) (*M, error) {
var m model[M]
return &m.Value, decoder.Decode(&m)
}
type repositoryMapper[A any, B any] interface {
Schema() string
Map(A) (B, error)
}
type MapDecoder[A any, B any] struct {
mapper repositoryMapper[A, B]
}
func NewMapDecoder[A any, B any](mapper repositoryMapper[A, B]) MapDecoder[A, B] {
return MapDecoder[A, B]{
mapper: mapper,
}
}
func (rd MapDecoder[A, B]) Schema() string {
return rd.mapper.Schema()
}
func (rd MapDecoder[A, B]) Decode(d Document) (*model[B], error) {
a, err := Decode[model[A]](d)
if err != nil {
return nil, err
}
b, err := rd.mapper.Map(a.Value)
if err != nil {
return nil, err
}
return &model[B]{
ID: a.ID,
Version: a.Version,
Schema: a.Schema,
Events: a.Events,
Value: b,
}, nil
}