12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- package handler
- //go:generate mkdir -p mocks
- //go:generate rm -rf ./mocks/*_minimock.go
- //go:generate minimock -i CacheService,ArticleRepository,TagRepository -o ./mocks/ -s "_minimock.go"
- import (
- "context"
- "time"
- "git.dmitriygnatenko.ru/dima/go-common/logger"
- "github.com/gofiber/fiber/v2"
- "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/mapper"
- "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/models"
- "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/services/i18n"
- )
- type (
- CacheService interface {
- Get(key string) (interface{}, bool)
- Set(key string, value interface{}, expiration *time.Duration)
- }
- ArticleRepository interface {
- GetByURL(ctx context.Context, url string, lang models.Language) (*models.Article, error)
- GetAllPreview(ctx context.Context, lang models.Language) ([]models.ArticlePreview, error)
- GetPreviewByTagID(ctx context.Context, tagID uint64, lang models.Language) ([]models.ArticlePreview, error)
- }
- TagRepository interface {
- GetAllUsed(ctx context.Context, lang models.Language) ([]models.Tag, error)
- GetByURL(ctx context.Context, tag string) (*models.Tag, error)
- }
- )
- const AllPreviewArticlesCacheKey = "all-preview-articles"
- func MainPageHandler(
- cacheService CacheService,
- articleRepository ArticleRepository,
- ) fiber.Handler {
- return func(fctx *fiber.Ctx) error {
- ctx := fctx.Context()
- lang := mapper.LanguageFromContext(fctx)
- cacheKey := AllPreviewArticlesCacheKey + string(lang)
- renderData, found := cacheService.Get(cacheKey)
- if !found {
- articles, err := articleRepository.GetAllPreview(ctx, mapper.ToLanguageModel(lang))
- if err != nil {
- logger.Error(ctx, err.Error())
- return err
- }
- renderData = fiber.Map{
- "lang": lang,
- "headTitle": i18n.T(lang, "head_title"),
- "pageTitle": i18n.T(lang, "main_page_title"),
- "headDescription": i18n.T(lang, "main_page_desc"),
- "headKeywords": i18n.T(lang, "main_page_keywords"),
- "articles": mapper.ToArticlesPreview(lang, articles),
- }
- cacheService.Set(cacheKey, renderData, nil)
- }
- return fctx.Render("index", renderData, "_layout")
- }
- }
|