package handler import ( "database/sql" "errors" "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/services/i18n" ) const ( ArticleCacheKey = "article" maxArticlesCount = 3 articleParam = "article" ) func ArticleHandler( cacheService CacheService, articleRepository ArticleRepository, tagRepository TagRepository, ) fiber.Handler { return func(fctx *fiber.Ctx) error { ctx := fctx.Context() url := fctx.Params(articleParam) lang := i18n.Language(fctx) renderData, found := cacheService.Get(ArticleCacheKey + string(lang) + url) if !found { article, err := articleRepository.GetByURL(ctx, url) if err != nil { if errors.Is(err, sql.ErrNoRows) { return fiber.ErrNotFound } logger.Error(ctx, err.Error()) return err } if !article.IsActive { return fiber.ErrNotFound } articleDTO := mapper.ToArticleDTO(fctx, *article) // All used tags tags, err := tagRepository.GetAllUsed(ctx) if err != nil { logger.Error(ctx, err.Error()) return err } tagsDTO := mapper.ToTagDTOList(tags) // Last articles articles, err := articleRepository.GetAllPreview(ctx) if err != nil { logger.Error(ctx, err.Error()) return err } if len(articles) > maxArticlesCount { articles = articles[:maxArticlesCount] } renderData = fiber.Map{ "headTitle": i18n.T(lang, "head_title"), "headDescription": articleDTO.MetaDescription, "headKeywords": articleDTO.MetaKeywords, "pageTitle": i18n.T(lang, "article_page_title", articleDTO.Title), "article": articleDTO, "sidebarArticles": mapper.ToArticlePreviewDTOList(fctx, articles), "sidebarTags": tagsDTO, } cacheService.Set(ArticleCacheKey+string(lang)+url, renderData, nil) } return fctx.Render("article", renderData, "_layout") } }