chore(repo): import lab2 sources as lab3 baseline
This commit is contained in:
@@ -0,0 +1,93 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
func (r *MessageRepo) Create(ctx context.Context, message *domain.Message) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
stored := *message
|
||||
r.messages[message.ChatID] = append(r.messages[message.ChatID], stored)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *MessageRepo) ListByChat(ctx context.Context, chatID string, limit int, cursor *string) ([]domain.Message, *string, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
|
||||
scope := "messages:" + chatID
|
||||
|
||||
var (
|
||||
afterTime time.Time
|
||||
afterID string
|
||||
hasCursor bool
|
||||
)
|
||||
if cursor != nil {
|
||||
t, id, err := decodeCursor(*cursor, scope)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
afterTime = t
|
||||
afterID = id
|
||||
hasCursor = true
|
||||
}
|
||||
|
||||
src := r.messages[chatID]
|
||||
if len(src) == 0 {
|
||||
return []domain.Message{}, nil, nil
|
||||
}
|
||||
|
||||
all := make([]domain.Message, len(src))
|
||||
copy(all, src)
|
||||
|
||||
slices.SortFunc(all, func(a, b domain.Message) int {
|
||||
if lessThan(a.CreatedAt, a.ID, b.CreatedAt, b.ID) {
|
||||
return -1
|
||||
}
|
||||
if lessThan(b.CreatedAt, b.ID, a.CreatedAt, a.ID) {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
})
|
||||
|
||||
start := 0
|
||||
if hasCursor {
|
||||
start = len(all)
|
||||
for i, m := range all {
|
||||
if lessThan(afterTime, afterID, m.CreatedAt, m.ID) {
|
||||
start = i
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if start >= len(all) {
|
||||
return []domain.Message{}, nil, nil
|
||||
}
|
||||
end := start + limit
|
||||
if end > len(all) {
|
||||
end = len(all)
|
||||
}
|
||||
page := all[start:end]
|
||||
|
||||
var next *string
|
||||
if end < len(all) {
|
||||
last := page[len(page)-1]
|
||||
c := encodeCursor(scope, last.CreatedAt, last.ID)
|
||||
next = &c
|
||||
}
|
||||
|
||||
return page, next, nil
|
||||
}
|
||||
Reference in New Issue
Block a user