article.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package handler
  2. import (
  3. "database/sql"
  4. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/interfaces"
  5. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/mapper"
  6. "github.com/gofiber/fiber/v2"
  7. )
  8. const (
  9. maxArticlesCount = 3
  10. articleParam = "article"
  11. articleCacheKey = "article"
  12. )
  13. func ArticleHandler(sp interfaces.ServiceProvider) fiber.Handler {
  14. return func(fctx *fiber.Ctx) error {
  15. ctx := fctx.Context()
  16. articleReq := fctx.Params(articleParam)
  17. renderData, found := sp.GetCacheService().Get(articleCacheKey + articleReq)
  18. if !found {
  19. article, err := sp.GetArticleRepository().GetByURL(ctx, articleReq)
  20. if err != nil {
  21. if err == sql.ErrNoRows {
  22. return fiber.ErrNotFound
  23. }
  24. return err
  25. }
  26. if !article.IsActive {
  27. return fiber.ErrNotFound
  28. }
  29. articleDTO := mapper.ConvertArticleModelToDTO(*article)
  30. // All used tags
  31. tags, err := sp.GetTagRepository().GetAllUsed(ctx)
  32. if err != nil {
  33. return err
  34. }
  35. tagsDTO := mapper.ConvertTagModelsToDTO(tags)
  36. // Last articles
  37. articles, err := sp.GetArticleRepository().GetAllPreview(ctx)
  38. if err != nil {
  39. return err
  40. }
  41. if len(articles) > maxArticlesCount {
  42. articles = articles[:maxArticlesCount]
  43. }
  44. renderData = fiber.Map{
  45. "headTitle": "От слона к суслику - статьи про PHP, Go, алгоритмы",
  46. "headDescription": articleDTO.MetaDescription,
  47. "headKeywords": articleDTO.MetaKeywords,
  48. "pageTitle": "Статья<br>" + articleDTO.Title,
  49. "article": articleDTO,
  50. "sidebarArticles": mapper.ConvertArticlePreviewModelsToDTO(articles),
  51. "sidebarTags": tagsDTO,
  52. }
  53. sp.GetCacheService().Set(articleCacheKey+articleReq, renderData)
  54. }
  55. return fctx.Render("article", renderData, "_layout")
  56. }
  57. }