/
map_device.go
101 lines (83 loc) · 2.08 KB
/
map_device.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
package adaptors
import (
"github.com/e154/smart-home/db"
m "github.com/e154/smart-home/models"
"github.com/jinzhu/gorm"
)
type MapDevice struct {
table *db.MapDevices
db *gorm.DB
}
func GetMapDeviceAdaptor(d *gorm.DB) *MapDevice {
return &MapDevice{
table: &db.MapDevices{Db: d},
db: d,
}
}
func (n *MapDevice) Add(ver *m.MapDevice) (id int64, err error) {
dbVer := n.toDb(ver)
if id, err = n.table.Add(dbVer); err != nil {
return
}
return
}
func (n *MapDevice) GetById(mapId int64) (ver *m.MapDevice, err error) {
var dbVer *db.MapDevice
if dbVer, err = n.table.GetById(mapId); err != nil {
return
}
ver = n.fromDb(dbVer)
return
}
func (n *MapDevice) Delete(mapId int64) (err error) {
err = n.table.Delete(mapId)
return
}
func (n *MapDevice) fromDb(dbVer *db.MapDevice) (ver *m.MapDevice) {
ver = &m.MapDevice{
Id: dbVer.Id,
SystemName: dbVer.SystemName,
DeviceId: dbVer.DeviceId,
ImageId: dbVer.ImageId,
Actions: make([]*m.MapDeviceAction, 0),
States: make([]*m.MapDeviceState, 0),
CreatedAt: dbVer.CreatedAt,
UpdatedAt: dbVer.UpdatedAt,
}
// actions
mapDeviceActionAdaptor := GetMapDeviceActionAdaptor(n.db)
for _, dbAction := range dbVer.Actions {
action := mapDeviceActionAdaptor.fromDb(dbAction)
ver.Actions = append(ver.Actions, action)
}
// states
mapDeviceStateAdaptor := GetMapDeviceStateAdaptor(n.db)
for _, dbState := range dbVer.States {
state := mapDeviceStateAdaptor.fromDb(dbState)
ver.States = append(ver.States, state)
}
// device
if dbVer.Device != nil {
deviceAdaptor := GetDeviceAdaptor(n.db)
ver.Device = deviceAdaptor.fromDb(dbVer.Device)
}
// image
if dbVer.Image != nil {
imageAdaptor := GetImageAdaptor(n.db)
ver.Image = imageAdaptor.fromDb(dbVer.Image)
}
return
}
func (n *MapDevice) toDb(ver *m.MapDevice) (dbVer *db.MapDevice) {
dbVer = &db.MapDevice{
Id: ver.Id,
SystemName: ver.SystemName,
DeviceId: ver.DeviceId,
}
if ver.ImageId != 0 {
dbVer.ImageId = ver.ImageId
} else if ver.Image != nil && ver.Image.Id != 0 {
dbVer.ImageId = ver.Image.Id
}
return
}