-
Notifications
You must be signed in to change notification settings - Fork 1
/
class_serializer.go
67 lines (54 loc) · 1.5 KB
/
class_serializer.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
package serialization
import (
"errors"
"github.com/goal-web/contracts"
"github.com/goal-web/serialization/serializers"
"github.com/goal-web/supports/class"
"reflect"
"sync"
)
type Class struct {
Class string `json:"c"`
Payload string `json:"p"`
}
func NewClassSerializer(container contracts.Container) contracts.ClassSerializer {
return &Serializer{
container: container,
classes: sync.Map{},
serializer: serializers.Json{},
}
}
type Serializer struct {
container contracts.Container
classes sync.Map
serializer contracts.Serializer
}
func (this *Serializer) Register(class contracts.Class) {
this.classes.Store(class.ClassName(), class)
}
func (this *Serializer) Serialize(instance interface{}) string {
return this.serializer.Serialize(Class{
Class: class.Make(instance).ClassName(),
Payload: this.serializer.Serialize(instance),
})
}
func (this *Serializer) Parse(serialized string) (interface{}, error) {
var c Class
if err := this.serializer.Unserialize(serialized, &c); err != nil {
return nil, err
}
classItem, exists := this.classes.Load(c.Class)
if !exists {
return nil, errors.New("unregistered class")
}
targetClass := classItem.(contracts.Class)
instance := reflect.New(targetClass.GetType()).Interface()
if err := this.serializer.Unserialize(c.Payload, instance); err != nil {
return nil, err
}
if component, isComponent := instance.(contracts.Component); isComponent {
component.Construct(this.container)
return component, nil
}
return instance, nil
}