Skip to content

Commit 96521b6

Browse files
committed
Implement GetChatByUsername
Signed-off-by: Elis Lulja <[email protected]>
1 parent c61e131 commit 96521b6

File tree

1 file changed

+35
-2
lines changed

1 file changed

+35
-2
lines changed

pkg/firestore/fs.go

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package firestore
22

33
import (
44
"context"
5+
"errors"
56
"fmt"
67
"os"
78
"path"
@@ -13,6 +14,7 @@ import (
1314
"github.com/SunSince90/kube-scraper-backend/pkg/backend"
1415
"github.com/SunSince90/kube-scraper-backend/pkg/pb"
1516
"github.com/rs/zerolog"
17+
"google.golang.org/api/iterator"
1618
"google.golang.org/api/option"
1719
"google.golang.org/grpc/codes"
1820
"google.golang.org/grpc/status"
@@ -123,8 +125,39 @@ func (f *fsBackend) GetChatByID(id int64) (*pb.Chat, error) {
123125

124126
// GetChatByUsername gets a chat from firestore by username
125127
func (f *fsBackend) GetChatByUsername(username string) (*pb.Chat, error) {
126-
// TODO: implement me
127-
return nil, nil
128+
// -- Init
129+
if len(username) == 0 {
130+
return nil, fmt.Errorf("chat username cannot be 0")
131+
}
132+
133+
l := log.With().Str("func", "GetChatByUsername").Str("username", username).Logger()
134+
ctx, canc := context.WithTimeout(context.Background(), timeout)
135+
defer canc()
136+
137+
// -- Get the chat
138+
docIter := f.client.Collection(f.ChatsCollection).Where("username", "==", username).Limit(1).Documents(ctx)
139+
doc, err := docIter.Next()
140+
if err != nil {
141+
if errors.Is(err, iterator.Done) {
142+
return nil, backend.ErrNotFound
143+
}
144+
145+
return nil, err
146+
}
147+
l.Debug().Msg("pulled from firestore")
148+
149+
// -- Cast and return
150+
var _chat chat
151+
if err := doc.DataTo(&_chat); err != nil {
152+
return nil, err
153+
}
154+
c := convertToProto(&_chat)
155+
156+
if f.UseCache {
157+
// TODO: implement cache
158+
}
159+
160+
return c, nil
128161
}
129162

130163
// StoreChats inserts a chat into firestore

0 commit comments

Comments
 (0)