us-coach-spider/server/spider.go
2024-11-21 14:36:31 +08:00

98 lines
2.5 KiB
Go

package server
import (
"fmt"
"strconv"
"gitea.timerzz.com/kedaya_haitao/coach-spider/spider"
"gitea.timerzz.com/kedaya_haitao/common/pkg/web"
v2 "gitea.timerzz.com/kedaya_haitao/common/structs/v2"
"github.com/gofiber/fiber/v3"
)
type SpiderSvc struct {
ctl *spider.Controller
providerId v2.ProviderId
}
func NewSpiderSvc(ctl *spider.Controller, providerId v2.ProviderId) *SpiderSvc {
return &SpiderSvc{
ctl: ctl,
providerId: providerId,
}
}
func (s *SpiderSvc) Registry(r fiber.Router) {
api := r.Group("/api/v2")
api.Post(fmt.Sprintf("provider/%s/pull", s.providerId), s.Pull)
api.Post(fmt.Sprintf("provider/%s/price/fetch/:id", s.providerId), s.FetchArticlePrice)
api.Post(fmt.Sprintf("provider/%s/detail/fetch/:pid", s.providerId), s.FetchArticleDetail)
api.Post(fmt.Sprintf("provider/%s/ats/fetch/:pid", s.providerId), s.FetchArticleAts)
//r.Post("spider/us/coach-outlet/calculate", s.UpsertCalculate)
//r.Delete("spider/us/coach-outlet/calculate/u/:id", s.DelCalculate)
}
func (s *SpiderSvc) Pull(ctx fiber.Ctx) error {
// 接收到,就爬取数据
go s.ctl.Crawl()
return ctx.JSON(web.NewResponse("ok", "ok"))
}
func (s *SpiderSvc) FetchArticlePrice(ctx fiber.Ctx) error {
i := ctx.Params("id")
id, _ := strconv.Atoi(i)
if id == 0 {
return fmt.Errorf("id is empty")
}
if err := s.ctl.FetchArticlePrice(ctx.Context(), uint(id)); err != nil {
return err
}
return ctx.JSON(web.NewResponse("ok"))
}
func (s *SpiderSvc) FetchArticleDetail(ctx fiber.Ctx) error {
pid := ctx.Params("pid")
if pid == "" {
return fmt.Errorf("pid is empty")
}
if err := s.ctl.FetchArticleDetail(ctx.Context(), pid); err != nil {
return err
}
return ctx.JSON(web.NewResponse("ok"))
}
func (s *SpiderSvc) FetchArticleAts(ctx fiber.Ctx) error {
pid := ctx.Params("pid")
if pid == "" {
return fmt.Errorf("pid is empty")
}
if err := s.ctl.FetchArticleAts(ctx.Context(), pid); err != nil {
return err
}
return ctx.JSON(web.NewResponse("ok"))
}
//func (s *SpiderSvc) DelCalculate(ctx fiber.Ctx) error {
// idStr := ctx.Params("id")
// if idStr == "" {
// return fiber.ErrBadRequest
// }
// id, _ := strconv.Atoi(idStr)
// if err := s.ctl.DeleteCalculateProcess(uint(id)); err != nil {
// return err
// }
// return nil
//}
//
//func (s *SpiderSvc) UpsertCalculate(ctx fiber.Ctx) error {
// var cs []productv1.CalculateProcess
// if err := ctx.Bind().JSON(&cs); err != nil {
// return err
// }
// if err := s.ctl.SaveCalculateProcess(cs); err != nil {
// return err
// }
// return nil
//}