Skip to content

Commit c61e131

Browse files
committed
Implement GetChatByID
Signed-off-by: Elis Lulja <[email protected]>
1 parent 4785b69 commit c61e131

File tree

2 files changed

+60
-2
lines changed

2 files changed

+60
-2
lines changed

pkg/firestore/fs.go

Lines changed: 45 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,22 @@ import (
44
"context"
55
"fmt"
66
"os"
7+
"path"
78
"sync"
9+
"time"
810

911
fs "cloud.google.com/go/firestore"
1012
firebase "firebase.google.com/go/v4"
1113
"github.com/SunSince90/kube-scraper-backend/pkg/backend"
1214
"github.com/SunSince90/kube-scraper-backend/pkg/pb"
1315
"github.com/rs/zerolog"
1416
"google.golang.org/api/option"
17+
"google.golang.org/grpc/codes"
18+
"google.golang.org/grpc/status"
19+
)
20+
21+
const (
22+
timeout = time.Duration(15) * time.Second
1523
)
1624

1725
var (
@@ -74,8 +82,43 @@ func (f *fsBackend) Close() {
7482

7583
// GetChatByID gets a chat from firestore
7684
func (f *fsBackend) GetChatByID(id int64) (*pb.Chat, error) {
77-
// TODO: implement me
78-
return nil, nil
85+
// -- Init
86+
if id == 0 {
87+
return nil, fmt.Errorf("chat id cannot be 0")
88+
}
89+
90+
l := log.With().Str("func", "GetChatByID").Int64("id", id).Logger()
91+
if f.UseCache {
92+
// TODO: implement cache
93+
}
94+
95+
// -- Get the chat
96+
docPath := path.Join(f.ChatsCollection, fmt.Sprintf("%d", id))
97+
ctx, canc := context.WithTimeout(context.Background(), timeout)
98+
defer canc()
99+
100+
doc, err := f.client.Doc(docPath).Get(ctx)
101+
if err != nil {
102+
if status.Code(err) == codes.NotFound {
103+
return nil, backend.ErrNotFound
104+
}
105+
106+
return nil, err
107+
}
108+
l.Debug().Msg("pulled from firestore")
109+
110+
// -- Cast and return
111+
var _chat chat
112+
if err := doc.DataTo(&_chat); err != nil {
113+
return nil, err
114+
}
115+
c := convertToProto(&_chat)
116+
117+
if f.UseCache {
118+
// TODO: implement cache
119+
}
120+
121+
return c, nil
79122
}
80123

81124
// GetChatByUsername gets a chat from firestore by username

pkg/firestore/utils.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package firestore
2+
3+
import (
4+
"github.com/SunSince90/kube-scraper-backend/pkg/pb"
5+
)
6+
7+
func convertToProto(c *chat) *pb.Chat {
8+
return &pb.Chat{
9+
Id: c.ChatID,
10+
Type: c.Type,
11+
Username: c.Username,
12+
FirstName: c.FirstName,
13+
LastName: c.LastName,
14+
}
15+
}

0 commit comments

Comments
 (0)