Files
backend_v2/internal/service/history_service.go
toom1996 1fd9c48f58 update
2026-09-02 21:51:35 +08:00

80 lines
2.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package service
import (
"context"
"time"
"fashionapi/internal/dto"
"fashionapi/internal/model"
"fashionapi/internal/repository"
)
// HistoryService 浏览历史业务接口。所有方法均要求调用方已通过中间件解析出 userID。
type HistoryService interface {
// Record 记录一次浏览:点开某篇文章详情时上报其对外编码串 id(upsert:同文章刷新时间)。
Record(ctx context.Context, userID uint32, req dto.HistoryAdd) error
// ListPaged 分页取当前用户历史(服务端分页)。
ListPaged(ctx context.Context, userID uint32, page, perPage int) ([]dto.HistoryItem, int64, error)
// Remove 删除某条历史。
Remove(ctx context.Context, userID uint32, targetUID string) error
// Clear 清空当前用户全部历史。
Clear(ctx context.Context, userID uint32) error
}
type historyService struct {
hist repository.HistoryRepository
}
// NewHistoryService 创建浏览历史服务。
func NewHistoryService(hist repository.HistoryRepository) HistoryService {
return &historyService{hist: hist}
}
func (s *historyService) Record(ctx context.Context, userID uint32, req dto.HistoryAdd) error {
if req.TargetUID == "" {
return badRequest("target_uid required")
}
row := &model.History{
UserID: userID,
TargetUID: req.TargetUID,
ViewedAt: uint32(time.Now().Unix()),
}
if err := s.hist.Upsert(ctx, row); err != nil {
return internalErr(err.Error())
}
return nil
}
func (s *historyService) ListPaged(ctx context.Context, userID uint32, page, perPage int) ([]dto.HistoryItem, int64, error) {
rows, err := s.hist.ListPaged(ctx, userID, page, perPage)
if err != nil {
return nil, 0, internalErr(err.Error())
}
total, err := s.hist.CountByUser(ctx, userID)
if err != nil {
return nil, 0, internalErr(err.Error())
}
out := make([]dto.HistoryItem, 0, len(rows))
for _, r := range rows {
out = append(out, dto.HistoryItem{ID: r.TargetUID, ViewedAt: r.ViewedAt})
}
return out, total, nil
}
func (s *historyService) Remove(ctx context.Context, userID uint32, targetUID string) error {
if targetUID == "" {
return badRequest("target_uid required")
}
if err := s.hist.Remove(ctx, userID, targetUID); err != nil {
return internalErr(err.Error())
}
return nil
}
func (s *historyService) Clear(ctx context.Context, userID uint32) error {
if err := s.hist.Clear(ctx, userID); err != nil {
return internalErr(err.Error())
}
return nil
}