* stash

* replace chats sql with store

* strip unused method
This commit is contained in:
Asim Aslam
2021-05-07 17:09:51 +01:00
committed by GitHub
parent 0ad35b9340
commit 542c105037
15 changed files with 410 additions and 315 deletions

View File

@@ -6,6 +6,7 @@ import (
"github.com/micro/micro/v3/service/auth"
"github.com/micro/micro/v3/service/errors"
"github.com/micro/micro/v3/service/logger"
"github.com/micro/micro/v3/service/store"
pb "github.com/micro/services/chats/proto"
)
@@ -23,33 +24,46 @@ func (c *Chats) ListMessages(ctx context.Context, req *pb.ListMessagesRequest, r
return ErrMissingChatID
}
db, err := c.GetDBConn(ctx)
if err != nil {
logger.Errorf("Error connecting to DB: %v", err)
return errors.InternalServerError("DB_ERROR", "Error connecting to DB")
}
// construct the query
q := db.Where(&Message{ChatID: req.ChatId}).Order("sent_at DESC")
if req.SentBefore != nil {
q = q.Where("sent_at < ?", req.SentBefore.AsTime())
}
if req.Limit != nil {
q.Limit(int(req.Limit.Value))
} else {
q.Limit(DefaultLimit)
message := &Message{
ChatID: req.ChatId,
}
// execute the query
var msgs []Message
if err := q.Find(&msgs).Error; err != nil {
// default order is descending
order := store.OrderDesc
if req.Order == "asc" {
order = store.OrderAsc
}
opts := []store.ReadOption{
store.ReadPrefix(),
store.ReadOrder(order),
}
if req.Limit > 0 {
opts = append(opts, store.ReadLimit(uint(req.Limit)))
} else {
opts = append(opts, store.ReadLimit(uint(DefaultLimit)))
}
if req.Offset > 0 {
opts = append(opts, store.ReadOffset(uint(req.Offset)))
}
// read all the records with the chat ID suffix
recs, err := store.Read(message.Index(ctx), opts...)
if err != nil {
logger.Errorf("Error reading messages: %v", err)
return errors.InternalServerError("DATABASE_ERROR", "Error connecting to database")
}
// serialize the response
rsp.Messages = make([]*pb.Message, len(msgs))
for i, m := range msgs {
rsp.Messages[i] = m.Serialize()
// return all the messages
for _, rec := range recs {
m := &Message{}
rec.Decode(&m)
if len(m.ID) == 0 || m.ChatID != req.ChatId {
continue
}
rsp.Messages = append(rsp.Messages, m.Serialize())
}
return nil
}