update
This commit is contained in:
79
internal/service/history_service.go
Normal file
79
internal/service/history_service.go
Normal file
@ -0,0 +1,79 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user