/
chat_room_repository.go
96 lines (80 loc) · 2.23 KB
/
chat_room_repository.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
package repository
import (
"bytes"
"os"
"time"
"github.com/go-redis/redis"
"github.com/tmpchat/tmpchat/message_broker/domain"
)
type ChatRoomRepository interface {
Create(roomID string) (*domain.ChatRoom, error)
Find(roomID string) (*domain.ChatRoom, error)
AddMessage(roomID string, message domain.ChatMessage) error
GetMessages(roomID string) ([]domain.ChatMessage, error)
Delete(roomID string) error
}
type chatRoomRepository struct {
db *redis.Client
}
// NewChatRoomRepository create ChatMessageRepository
func NewChatRoomRepository() ChatRoomRepository {
return chatRoomRepository{newRedisClient()}
}
// TODO: config の整理、他の repository でも使用する可能性があるので別のファイルに分ける。
func newRedisClient() *redis.Client {
redisHost := os.Getenv("REDIS_HOST")
if redisHost == "" {
redisHost = "localhost:6379"
}
client := redis.NewClient(&redis.Options{
Addr: redisHost,
Password: "", // no password set
DB: 0, // use default DB
})
return client
}
func (c chatRoomRepository) Create(roomID string) (*domain.ChatRoom, error) {
now := time.Now()
room := domain.ChatRoom{ID: roomID, CreatedAt: now, UpdateAt: now}
if err := c.db.Set(room.ID, room, 0).Err(); err != nil {
return nil, err
}
return &room, nil
}
func (c chatRoomRepository) Find(roomID string) (*domain.ChatRoom, error) {
raw, err := c.db.Get(roomID).Result()
if err != nil {
return nil, err
}
room := domain.ChatRoom{}
if err := room.UnmarshalBinary(bytes.NewBufferString(raw).Bytes()); err != nil {
return nil, err
}
return &room, nil
}
func (c chatRoomRepository) AddMessage(roomID string, message domain.ChatMessage) error {
room, err := c.Find(roomID)
if err != nil {
return err
}
// TODO: duplication check message id
room.Messages = append(room.Messages, message)
room.UpdateAt = time.Now()
if err := c.db.Set(roomID, room, 0).Err(); err != nil {
return err
}
return nil
}
func (c chatRoomRepository) GetMessages(roomID string) ([]domain.ChatMessage, error) {
room, err := c.Find(roomID)
if err != nil {
return nil, err
}
return room.Messages, nil
}
func (c chatRoomRepository) Delete(roomID string) error {
if err := c.db.Del(roomID).Err(); err != nil {
return err
}
return nil
}