-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjourney_store.go
71 lines (57 loc) · 1.48 KB
/
journey_store.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
package tgf
import (
"errors"
"sync"
)
type Journey struct {
ID string
TelegramChatID int64
ChatID int64
Command string
Next int
RawContext []byte
MessagesCleanup []int
}
var (
JourneyNotFoundErr = errors.New("journey not found")
)
type JourneyStore interface {
GetJourneyByChatID(chatID int64) (*Journey, error)
CleanupChatJourney(chatID int64) error
UpsertJourneyByTelegeramChatID(chatID int64, upsert Journey) (*Journey, error)
}
// TODO: maybe switch this for a rwmutex implementation?
// that way I can get type safety, not that it matters that much
type InMemJourneyStore struct {
journeyMap sync.Map
}
func NewInMemJourneyStore() *InMemJourneyStore {
return &InMemJourneyStore{}
}
func (s *InMemJourneyStore) GetJourneyByChat(chatID int64) (*Journey, error) {
j, ok := s.journeyMap.Load(chatID)
if !ok {
return nil, JourneyNotFoundErr
}
journey, ok := j.(Journey)
if !ok {
return nil, errors.New("type assertion failed")
}
return &journey, nil
}
func (s *InMemJourneyStore) CleanupChatJourney(chatID int64) error {
s.journeyMap.Delete(chatID)
return nil
}
func (s *InMemJourneyStore) UpsertJourneyByTelegeramChatID(chatID int64, upsert Journey) (*Journey, error) {
s.journeyMap.Store(chatID, upsert)
j, ok := s.journeyMap.Load(chatID)
if !ok {
return nil, errors.New("type assertion failed")
}
journey, ok := j.(Journey)
if !ok {
return nil, errors.New("type assertion failed")
}
return &journey, nil
}