88 lines
2.2 KiB
Go
88 lines
2.2 KiB
Go
package repositories
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
type Message struct {
|
|
ID string `json:"id"`
|
|
ChatID string `json:"chat_id"`
|
|
SenderID string `json:"sender_id"`
|
|
Text string `json:"text"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
}
|
|
|
|
type MessageStore struct {
|
|
db *pgxpool.Pool
|
|
idempotencyTTL time.Duration
|
|
}
|
|
|
|
func NewMessageStore(db *pgxpool.Pool) *MessageStore {
|
|
return NewMessageStoreWithTTL(db, 24*time.Hour)
|
|
}
|
|
|
|
func NewMessageStoreWithTTL(db *pgxpool.Pool, ttl time.Duration) *MessageStore {
|
|
return &MessageStore{db: db, idempotencyTTL: ttl}
|
|
}
|
|
|
|
func (s *MessageStore) Create(
|
|
ctx context.Context,
|
|
chatID string,
|
|
senderID string,
|
|
text string,
|
|
) (Message, error) {
|
|
ctx, cancel := boundedQuery(ctx)
|
|
defer cancel()
|
|
message := Message{
|
|
ID: uuid.New().String(),
|
|
ChatID: chatID,
|
|
SenderID: senderID,
|
|
Text: text,
|
|
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
|
|
}
|
|
|
|
_, err := s.db.Exec(ctx, "INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES($1,$2,$3,$4,$5)", message.ID, message.ChatID, message.SenderID, message.Text, message.CreatedAt)
|
|
return message, err
|
|
}
|
|
|
|
func (s *MessageStore) ListPageByChat(
|
|
ctx context.Context,
|
|
chatID string,
|
|
cursor *MessageCursor,
|
|
limit int,
|
|
) ([]Message, bool, error) {
|
|
ctx, cancel := boundedQuery(ctx)
|
|
defer cancel()
|
|
afterTime := time.Time{}
|
|
afterID := "00000000-0000-0000-0000-000000000000"
|
|
if cursor != nil {
|
|
afterTime = cursor.CreatedAt
|
|
afterID = cursor.MessageID
|
|
}
|
|
rows, err := s.db.Query(ctx, `SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE chat_id=$1 AND (created_at,id)>($2,$3::uuid) ORDER BY created_at,id LIMIT $4`, chatID, afterTime, afterID, limit+1)
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
defer rows.Close()
|
|
items := []Message{}
|
|
for rows.Next() {
|
|
var m Message
|
|
if err = rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
|
|
return nil, false, err
|
|
}
|
|
items = append(items, m)
|
|
}
|
|
if err = rows.Err(); err != nil {
|
|
return nil, false, err
|
|
}
|
|
more := len(items) > limit
|
|
if more {
|
|
items = items[:limit]
|
|
}
|
|
return items, more, nil
|
|
}
|