/
db.go
80 lines (65 loc) · 1.58 KB
/
db.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 common
import (
"os"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/guregu/dynamo"
)
type Room struct {
RoomID string `dynamo:"roomId"`
Clients []Client `dynamo:"clients"`
Created time.Time `dynamo:"created"`
}
type Client struct {
ConnectionID string `dynamo:"connectionId"`
ClientID string `dynamo:"clientId"`
Joined time.Time `dynamo:"joined"`
}
type Connection struct {
ConnectionID string `dynamo:"connectionId"`
RoomID string `dynamo:"roomId"`
}
type DynamoDB struct {
db *dynamo.DB
}
type DynamoTable struct {
table dynamo.Table
}
func (d DynamoDB) Table(name string) Table {
return &DynamoTable{
table: d.db.Table(name),
}
}
func (d *DynamoDB) TxPut(items ...TableItem) error {
tx := d.db.WriteTx()
for _, item := range items {
t := item.Table.(*DynamoTable)
tx.Put(t.table.Put(item.Item))
}
return tx.Run()
}
func (d DynamoDB) RoomsTable() Table {
return &DynamoTable{
table: d.db.Table(os.Getenv("ROOM_TABLE_NAME")),
}
}
func (d DynamoDB) ConnectionsTable() Table {
return &DynamoTable{
table: d.db.Table(os.Getenv("CONNECTION_TABLE_NAME")),
}
}
func (t DynamoTable) FindOne(column string, key, out interface{}) error {
return t.table.Get(column, key).One(out)
}
func (t DynamoTable) Put(item interface{}) error {
return t.table.Put(item).Run()
}
func (t DynamoTable) Delete(column string, key interface{}) error {
return t.table.Delete(column, key).Run()
}
func NewDB(sess *session.Session, config *aws.Config) DB {
return &DynamoDB{
db: dynamo.New(sess, config),
}
}