tag.go 2.1 KB

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