1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- package handler
- import (
- "database/sql"
- "github.com/dmitriygnatenko/internal/interfaces"
- "github.com/dmitriygnatenko/internal/mapper"
- "github.com/gofiber/fiber/v2"
- )
- const (
- maxArticlesCount = 3
- articleCacheKey = "article"
- )
- func ArticleHandler(sp interfaces.IServiceProvider) fiber.Handler {
- return func(ctx *fiber.Ctx) error {
- articleReq := ctx.Params("article")
- renderData, found := sp.GetCacheService().Get(articleCacheKey + articleReq)
- if !found {
- article, err := sp.GetArticleRepository().GetByURL(ctx.Context(), articleReq)
- if err != nil {
- if err == sql.ErrNoRows {
- return fiber.ErrNotFound
- }
- return err
- }
- if !article.IsActive {
- return fiber.ErrNotFound
- }
- articleDTO, err := mapper.ConvertArticleModelToDTO(*article)
- if err != nil {
- return err
- }
- // All used tags
- tags, err := sp.GetTagRepository().GetAllUsed(ctx.Context())
- if err != nil {
- return err
- }
- tagsDTO, err := mapper.ConvertTagModelsToDTO(tags)
- if err != nil {
- return err
- }
- // Last articles
- articles, err := sp.GetArticleRepository().GetAllPreview(ctx.Context())
- if err != nil {
- return err
- }
- if len(articles) > maxArticlesCount {
- articles = articles[:maxArticlesCount]
- }
- articlesDTO, err := mapper.ConvertArticlePreviewModelsToDTO(articles)
- if err != nil {
- return err
- }
- renderData = fiber.Map{
- "headTitle": "От слона к суслику - статьи про PHP, Go, алгоритмы",
- "headDescription": articleDTO.MetaDescription,
- "headKeywords": articleDTO.MetaKeywords,
- "pageTitle": "Статья<br>" + articleDTO.Title,
- "article": articleDTO,
- "sidebarArticles": articlesDTO,
- "sidebarTags": tagsDTO,
- }
- sp.GetCacheService().Set(articleCacheKey+articleReq, renderData)
- }
- return ctx.Render("article", renderData, "_layout")
- }
- }
|