tag.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/mapper"
  8. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/services/i18n"
  9. )
  10. const (
  11. TagCacheKey = "tag"
  12. tagParam = "tag"
  13. )
  14. func TagHandler(
  15. cacheService CacheService,
  16. articleRepository ArticleRepository,
  17. tagRepository TagRepository,
  18. ) fiber.Handler {
  19. return func(fctx *fiber.Ctx) error {
  20. ctx := fctx.Context()
  21. url := fctx.Params(tagParam)
  22. lang := mapper.LanguageFromContext(fctx)
  23. cacheKey := TagCacheKey + url + string(lang)
  24. renderData, found := cacheService.Get(cacheKey)
  25. if !found {
  26. tag, err := tagRepository.GetByURL(ctx, url)
  27. if err != nil {
  28. if errors.Is(err, sql.ErrNoRows) {
  29. return fiber.ErrNotFound
  30. }
  31. logger.Error(ctx, err.Error())
  32. return err
  33. }
  34. articles, err := articleRepository.GetPreviewByTagID(ctx, tag.ID, mapper.ToLanguageModel(lang))
  35. if err != nil {
  36. logger.Error(ctx, err.Error())
  37. return err
  38. }
  39. renderData = fiber.Map{
  40. "lang": lang,
  41. "headTitle": i18n.T(lang, "head_title"),
  42. "pageTitle": i18n.T(lang, "tag_page_title", tag.Tag),
  43. "headDescription": i18n.T(lang, "tag_page_desc", tag.Tag),
  44. "headKeywords": i18n.T(lang, "tag_page_keywords", tag.Tag),
  45. "articles": mapper.ToArticlesPreview(lang, articles),
  46. }
  47. cacheService.Set(cacheKey, renderData, nil)
  48. }
  49. return fctx.Render("tag", renderData, "_layout")
  50. }
  51. }