main_page.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package handler
  2. import (
  3. "git.dmitriygnatenko.ru/dima/go-common/logger"
  4. "github.com/gofiber/fiber/v2"
  5. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/helpers/errors"
  6. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/mapper"
  7. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/services/i18n"
  8. )
  9. const AllPreviewArticlesCacheKey = "all-preview-articles"
  10. type mainPage struct {
  11. cacheService CacheService
  12. articleRepository ArticleRepository
  13. }
  14. func NewMainPageHandler(
  15. cacheService CacheService,
  16. articleRepository ArticleRepository,
  17. ) fiber.Handler {
  18. h := mainPage{
  19. cacheService: cacheService,
  20. articleRepository: articleRepository,
  21. }
  22. return h.handler()
  23. }
  24. func (h mainPage) handler() fiber.Handler {
  25. return func(fctx *fiber.Ctx) error {
  26. ctx := fctx.Context()
  27. lang := i18n.LanguageFromContext(fctx)
  28. cacheKey := AllPreviewArticlesCacheKey + string(lang)
  29. renderData, found := h.cacheService.Get(cacheKey)
  30. if !found {
  31. articleModels, err := h.articleRepository.GetAllPreview(ctx, i18n.LanguageID(lang))
  32. if err != nil {
  33. logger.Error(ctx, errors.Wrap(err, "main page: can't get articles").Error())
  34. return err
  35. }
  36. renderData = fiber.Map{
  37. "lang": lang,
  38. "headTitle": i18n.T(lang, "head_title"),
  39. "pageTitle": i18n.T(lang, "main_page_title"),
  40. "headDescription": i18n.T(lang, "main_page_desc"),
  41. "headKeywords": i18n.T(lang, "main_page_keywords"),
  42. "articles": mapper.ToArticlesPreview(lang, articleModels),
  43. }
  44. h.cacheService.Set(cacheKey, renderData, nil)
  45. }
  46. return fctx.Render("index", renderData, "_layout")
  47. }
  48. }