-
Notifications
You must be signed in to change notification settings - Fork 64
/
in_memory_social_graph_store.go
104 lines (80 loc) · 2.25 KB
/
in_memory_social_graph_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
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
102
103
104
package social_graph_manager
import (
"errors"
om "github.com/the-gigi/delinkcious/pkg/object_model"
)
type Followers map[string]bool
type Following map[string]bool
type SocialUser struct {
Username string
Followers Followers
Following Following
}
func NewSocialUser(username string) (user *SocialUser, err error) {
if username == "" {
err = errors.New("user name can't be empty")
return
}
user = &SocialUser{Username: username, Followers: Followers{}, Following: Following{}}
return
}
type SocialGraph map[string]*SocialUser
type InMemorySocialGraphStore struct {
socialGraph SocialGraph
}
func NewInMemorySocialGraphStore() om.SocialGraphManager {
return &InMemorySocialGraphStore{
socialGraph: SocialGraph{},
}
}
func (m *InMemorySocialGraphStore) Follow(followed string, follower string) (err error) {
followedUser := m.socialGraph[followed]
if followedUser == nil {
followedUser, _ = NewSocialUser(followed)
m.socialGraph[followed] = followedUser
}
if followedUser.Followers[follower] {
return errors.New("already following")
}
followedUser.Followers[follower] = true
followerUser := m.socialGraph[follower]
if followerUser == nil {
followerUser, _ = NewSocialUser(follower)
m.socialGraph[follower] = followerUser
}
followerUser.Following[followed] = true
return
}
func (m *InMemorySocialGraphStore) Unfollow(followed string, follower string) (err error) {
followedUser := m.socialGraph[followed]
if followedUser == nil {
err = errors.New("followed user doesn't exist")
return
}
if !followedUser.Followers[follower] {
err = errors.New("follower doesn't follow followed")
return
}
followedUser.Followers[follower] = false
followerUser := m.socialGraph[follower]
if followerUser == nil {
err = errors.New("follower user doesn't exist")
return
}
followerUser.Following[followed] = false
return
}
func (m *InMemorySocialGraphStore) GetFollowing(username string) (map[string]bool, error) {
user := m.socialGraph[username]
if user == nil {
return map[string]bool{}, nil
}
return user.Following, nil
}
func (m *InMemorySocialGraphStore) GetFollowers(username string) (map[string]bool, error) {
user := m.socialGraph[username]
if user == nil {
return map[string]bool{}, nil
}
return user.Followers, nil
}