main_page.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package handler
  2. //go:generate mkdir -p mocks
  3. //go:generate rm -rf ./mocks/*_minimock.go
  4. //go:generate minimock -i CacheService,ArticleRepository,TagRepository -o ./mocks/ -s "_minimock.go"
  5. import (
  6. "context"
  7. "time"
  8. "git.dmitriygnatenko.ru/dima/go-common/logger"
  9. "github.com/gofiber/fiber/v2"
  10. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/mapper"
  11. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/models"
  12. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/services/i18n"
  13. )
  14. type (
  15. CacheService interface {
  16. Get(key string) (interface{}, bool)
  17. Set(key string, value interface{}, expiration *time.Duration)
  18. }
  19. ArticleRepository interface {
  20. GetByURL(ctx context.Context, url string) (*models.Article, error)
  21. GetAllPreview(ctx context.Context) ([]models.ArticlePreview, error)
  22. GetPreviewByTagID(ctx context.Context, tagID uint64) ([]models.ArticlePreview, error)
  23. }
  24. TagRepository interface {
  25. GetAllUsed(ctx context.Context) ([]models.Tag, error)
  26. GetByURL(ctx context.Context, tag string) (*models.Tag, error)
  27. }
  28. )
  29. const allPreviewArticlesCacheKey = "all-preview-articles"
  30. func MainPageHandler(
  31. cacheService CacheService,
  32. articleRepository ArticleRepository,
  33. ) fiber.Handler {
  34. return func(fctx *fiber.Ctx) error {
  35. ctx := fctx.Context()
  36. lang := i18n.Language(fctx)
  37. renderData, found := cacheService.Get(allPreviewArticlesCacheKey + string(lang))
  38. if !found {
  39. articles, err := articleRepository.GetAllPreview(fctx.Context())
  40. if err != nil {
  41. logger.Error(ctx, err.Error())
  42. return err
  43. }
  44. renderData = fiber.Map{
  45. "headTitle": i18n.T(lang, "head_title"),
  46. "pageTitle": i18n.T(lang, "main_page_title"),
  47. "headDescription": i18n.T(lang, "main_page_desc"),
  48. "headKeywords": i18n.T(lang, "main_page_keywords"),
  49. "articles": mapper.ToArticlePreviewDTOList(fctx, articles),
  50. }
  51. cacheService.Set(allPreviewArticlesCacheKey+string(lang), renderData, nil)
  52. }
  53. return fctx.Render("index", renderData, "_layout")
  54. }
  55. }