/
connection.go
80 lines (71 loc) · 2.21 KB
/
connection.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
package resource
import (
"github.com/gbl08ma/sqalx"
"github.com/ulule/deepcopier"
"github.com/underlx/disturbancesmlx/types"
"github.com/yarf-framework/yarf"
)
// Connection composites resource
type Connection struct {
resource
}
type apiConnection struct {
From *types.Station `msgpack:"-" json:"-"`
To *types.Station `msgpack:"-" json:"-"`
//FromPlatform string `msgpack:"from_platform" json:"from_platform"`
//ToPlatform string `msgpack:"to_platform" json:"to_platform"`
TypicalWaitingSeconds int `msgpack:"typWaitS" json:"typWaitS"`
TypicalStopSeconds int `msgpack:"typStopS" json:"typStopS"`
TypicalSeconds int `msgpack:"typS" json:"typS"`
WorldLength int `msgpack:"worldLength" json:"worldLength"`
}
type apiConnectionWrapper struct {
apiConnection `msgpack:",inline"`
FromID string `msgpack:"from" json:"from"`
ToID string `msgpack:"to" json:"to"`
}
// WithNode associates a sqalx Node with this resource
func (r *Connection) WithNode(node sqalx.Node) *Connection {
r.node = node
return r
}
// Get serves HTTP GET requests on this resource
func (r *Connection) Get(c *yarf.Context) error {
tx, err := r.Beginx()
if err != nil {
return err
}
defer tx.Commit() // read-only tx
compat := c.Request.URL.Query().Get("closedcompat") != "false"
if c.Param("from") != "" && c.Param("to") != "" {
connection, err := types.GetConnection(tx, c.Param("from"), c.Param("to"), compat)
if err != nil {
return err
}
ac := &apiConnection{}
deepcopier.Copy(*connection).To(ac)
data := apiConnectionWrapper{
apiConnection: *ac,
FromID: connection.From.ID,
ToID: connection.To.ID,
}
RenderData(c, data, "s-maxage=10")
} else {
connections, err := types.GetConnections(tx, compat)
if err != nil {
return err
}
apiconnections := make([]apiConnectionWrapper, len(connections))
for i := range connections {
ac := &apiConnection{}
deepcopier.Copy(*connections[i]).To(ac)
apiconnections[i] = apiConnectionWrapper{
apiConnection: *ac,
FromID: connections[i].From.ID,
ToID: connections[i].To.ID,
}
}
RenderData(c, apiconnections, "s-maxage=10")
}
return nil
}