forked from 99designs/gqlgen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resolvers.go
120 lines (97 loc) · 2.34 KB
/
resolvers.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
//go:generate gorunpkg github.com/99designs/gqlgen
package chat
import (
context "context"
"math/rand"
"sync"
"time"
)
type resolver struct {
Rooms map[string]*Chatroom
mu sync.Mutex // nolint: structcheck
}
func (r *resolver) Mutation() MutationResolver {
return &mutationResolver{r}
}
func (r *resolver) Query() QueryResolver {
return &queryResolver{r}
}
func (r *resolver) Subscription() SubscriptionResolver {
return &subscriptionResolver{r}
}
func New() Config {
return Config{
Resolvers: &resolver{
Rooms: map[string]*Chatroom{},
},
}
}
type Chatroom struct {
Name string
Messages []Message
Observers map[string]chan Message
}
type mutationResolver struct{ *resolver }
func (r *mutationResolver) Post(ctx context.Context, text string, username string, roomName string) (Message, error) {
r.mu.Lock()
room := r.Rooms[roomName]
if room == nil {
room = &Chatroom{Name: roomName, Observers: map[string]chan Message{}}
r.Rooms[roomName] = room
}
r.mu.Unlock()
message := Message{
ID: randString(8),
CreatedAt: time.Now(),
Text: text,
CreatedBy: username,
}
room.Messages = append(room.Messages, message)
r.mu.Lock()
for _, observer := range room.Observers {
observer <- message
}
r.mu.Unlock()
return message, nil
}
type queryResolver struct{ *resolver }
func (r *queryResolver) Room(ctx context.Context, name string) (*Chatroom, error) {
r.mu.Lock()
room := r.Rooms[name]
if room == nil {
room = &Chatroom{Name: name, Observers: map[string]chan Message{}}
r.Rooms[name] = room
}
r.mu.Unlock()
return room, nil
}
type subscriptionResolver struct{ *resolver }
func (r *subscriptionResolver) MessageAdded(ctx context.Context, roomName string) (<-chan Message, error) {
r.mu.Lock()
room := r.Rooms[roomName]
if room == nil {
room = &Chatroom{Name: roomName, Observers: map[string]chan Message{}}
r.Rooms[roomName] = room
}
r.mu.Unlock()
id := randString(8)
events := make(chan Message, 1)
go func() {
<-ctx.Done()
r.mu.Lock()
delete(room.Observers, id)
r.mu.Unlock()
}()
r.mu.Lock()
room.Observers[id] = events
r.mu.Unlock()
return events, nil
}
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func randString(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
return string(b)
}