tag.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package handler
  2. import (
  3. "git.dmitriygnatenko.ru/dima/go-common/db"
  4. "git.dmitriygnatenko.ru/dima/go-common/logger"
  5. "github.com/gofiber/fiber/v2"
  6. customErrors "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/helper/errors"
  7. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/mapper"
  8. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/service/i18n"
  9. )
  10. const (
  11. TagCacheKey = "tag"
  12. tagParam = "tag"
  13. )
  14. type tagPage struct {
  15. cacheService CacheService
  16. articleRepository ArticleRepository
  17. tagRepository TagRepository
  18. }
  19. func NewTagPageHandler(
  20. cacheService CacheService,
  21. articleRepository ArticleRepository,
  22. tagRepository TagRepository,
  23. ) fiber.Handler {
  24. h := tagPage{
  25. cacheService: cacheService,
  26. articleRepository: articleRepository,
  27. tagRepository: tagRepository,
  28. }
  29. return h.handler()
  30. }
  31. func (h *tagPage) handler() fiber.Handler {
  32. return func(fctx *fiber.Ctx) error {
  33. ctx := fctx.Context()
  34. url := fctx.Params(tagParam)
  35. lang := i18n.LanguageFromContext(fctx)
  36. cacheKey := TagCacheKey + url + string(lang)
  37. renderData, found := h.cacheService.Get(cacheKey)
  38. if !found {
  39. tag, err := h.tagRepository.GetByURL(ctx, url)
  40. if err != nil {
  41. if db.IsNotFoundError(err) {
  42. return fiber.ErrNotFound
  43. }
  44. logger.Error(ctx, customErrors.Wrap(err, "tag page: can't get tag").Error())
  45. return err
  46. }
  47. articleModels, err := h.articleRepository.GetPreviewByTagID(
  48. ctx,
  49. tag.ID,
  50. i18n.LanguageID(lang),
  51. )
  52. if err != nil {
  53. logger.Error(ctx, customErrors.Wrap(err, "tag page: can't get articles").Error())
  54. return err
  55. }
  56. renderData = fiber.Map{
  57. "lang": lang,
  58. "headTitle": i18n.T(lang, "head_title"),
  59. "pageTitle": i18n.T(lang, "tag_page_title", tag.Tag),
  60. "headDescription": i18n.T(lang, "tag_page_desc", tag.Tag),
  61. "headKeywords": i18n.T(lang, "tag_page_keywords", tag.Tag),
  62. "articles": mapper.ToArticlesPreview(lang, articleModels),
  63. }
  64. h.cacheService.Set(cacheKey, renderData, nil)
  65. }
  66. return fctx.Render("tag", renderData, "_layout")
  67. }
  68. }