Files
mtusi2026lab3/internal/service/production/pages.go
T

50 lines
1.8 KiB
Go

package production
import (
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/cursor"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service"
)
// chatPage adapts the shared page result to the chat response DTO.
func (s *Service) chatPage(items []dto.ChatDTO, page pagination) (dto.ChatPageDTO, error) {
items, next, err := buildPage(items, page, s.cursors, chatPosition)
if err != nil {
return dto.ChatPageDTO{}, err
}
return dto.ChatPageDTO{Items: items, NextCursor: next}, nil
}
// messagePage adapts the shared page result to the message response DTO.
func (s *Service) messagePage(items []dto.MessageDTO, page pagination) (dto.MessagePageDTO, error) {
items, next, err := buildPage(items, page, s.cursors, messagePosition)
if err != nil {
return dto.MessagePageDTO{}, err
}
return dto.MessagePageDTO{Items: items, NextCursor: next}, nil
}
// buildPage trims lookahead and signs the last returned record when more data exists.
// The page limit must be validated before calling this helper.
func buildPage[T any](items []T, page pagination, codec service.CursorCodec, position func(T) cursor.Position) ([]T, *string, error) {
if len(items) <= page.limit {
return items, nil, nil
}
items = items[:page.limit]
next, err := codec.Encode(page.resource, position(items[len(items)-1]))
if err != nil {
return nil, nil, err
}
return items, new(next), nil
}
// chatPosition extracts the stable pagination boundary from a stored chat.
func chatPosition(chat dto.ChatDTO) cursor.Position {
return cursor.Position{CreatedAt: chat.CreatedAt, ID: chat.ID}
}
// messagePosition extracts the stable pagination boundary from a stored message.
func messagePosition(message dto.MessageDTO) cursor.Position {
return cursor.Position{CreatedAt: message.CreatedAt, ID: message.ID}
}