diff --git a/main.go b/main.go index cf71a5d..66ae8a3 100644 --- a/main.go +++ b/main.go @@ -65,6 +65,7 @@ func InitApp() *fx.App { extension.RegisterToolFunc, extension.RegisterPaginationFunc, extension.RegisterPostFunc, + extension.RegisterStatisticFunc, func(s *handler.Server) { s.RegisterRouters() }, diff --git a/template/extension/post.go b/template/extension/post.go index 72e6c6f..8730d0b 100644 --- a/template/extension/post.go +++ b/template/extension/post.go @@ -39,6 +39,7 @@ func RegisterPostFunc(template *template.Template, postService service.PostServi p.addListPostByCategorySlug() p.addListPostByTagID() p.addListPostByTagSlug() + p.addListMostPopularPost() } func (p *postExtension) addListLatestPost() { @@ -62,6 +63,27 @@ func (p *postExtension) addListLatestPost() { p.Template.AddFunc("listLatestPost", listLatestPostFunc) } +func (p *postExtension) addListMostPopularPost() { + listMostPopularPost := func(top int) ([]*vo.Post, error) { + ctx := context.Background() + posts, _, err := p.PostService.Page(ctx, param.PostQuery{ + Page: param.Page{ + PageNum: 0, + PageSize: top, + }, + Sort: ¶m.Sort{ + Fields: []string{"visits,desc"}, + }, + Statuses: []*consts.PostStatus{consts.PostStatusPublished.Ptr()}, + }) + if err != nil { + return nil, err + } + return p.PostAssembler.ConvertToListVO(ctx, posts) + } + p.Template.AddFunc("listMostPopularPost", listMostPopularPost) +} + func (p *postExtension) addGetPostCount() { getPostCountFunc := func() (int64, error) { ctx := context.Background() diff --git a/template/extension/statistic.go b/template/extension/statistic.go new file mode 100644 index 0000000..ceffed5 --- /dev/null +++ b/template/extension/statistic.go @@ -0,0 +1,34 @@ +package extension + +import ( + "context" + + "github.com/go-sonic/sonic/model/dto" + "github.com/go-sonic/sonic/service" + "github.com/go-sonic/sonic/template" +) + +type statisticExtension struct { + Template *template.Template + StatisticService service.StatisticService +} + +func RegisterStatisticFunc(template *template.Template, statisticService service.StatisticService) { + s := &statisticExtension{ + Template: template, + StatisticService: statisticService, + } + s.addGetStatisticsData() +} + +func (s *statisticExtension) addGetStatisticsData() { + getStatisticsDataFunc := func() (*dto.Statistic, error) { + ctx := context.Background() + statistic, err := s.StatisticService.Statistic(ctx) + if err != nil { + return nil, err + } + return statistic, nil + } + s.Template.AddFunc("getStatisticsData", getStatisticsDataFunc) +}