main_page.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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, lang models.Language) (*models.Article, error)
  21. GetAllPreview(ctx context.Context, lang models.Language) ([]models.ArticlePreview, error)
  22. GetPreviewByTagID(ctx context.Context, tagID uint64, lang models.Language) ([]models.ArticlePreview, error)
  23. }
  24. TagRepository interface {
  25. GetAllUsed(ctx context.Context, lang models.Language) ([]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 := mapper.LanguageFromContext(fctx)
  37. cacheKey := AllPreviewArticlesCacheKey + string(lang)
  38. renderData, found := cacheService.Get(cacheKey)
  39. if !found {
  40. articles, err := articleRepository.GetAllPreview(ctx, mapper.ToLanguageModel(lang))
  41. if err != nil {
  42. logger.Error(ctx, err.Error())
  43. return err
  44. }
  45. renderData = fiber.Map{
  46. "lang": lang,
  47. "headTitle": i18n.T(lang, "head_title"),
  48. "pageTitle": i18n.T(lang, "main_page_title"),
  49. "headDescription": i18n.T(lang, "main_page_desc"),
  50. "headKeywords": i18n.T(lang, "main_page_keywords"),
  51. "articles": mapper.ToArticlesPreview(lang, articles),
  52. }
  53. cacheService.Set(cacheKey, renderData, nil)
  54. }
  55. return fctx.Render("index", renderData, "_layout")
  56. }
  57. }