article.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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(ctx *fiber.Ctx) error {
  15. articleReq := ctx.Params(articleParam)
  16. renderData, found := sp.GetCacheService().Get(articleCacheKey + articleReq)
  17. if !found {
  18. article, err := sp.GetArticleRepository().GetByURL(ctx.Context(), articleReq)
  19. if err != nil {
  20. if err == sql.ErrNoRows {
  21. return fiber.ErrNotFound
  22. }
  23. return err
  24. }
  25. if !article.IsActive {
  26. return fiber.ErrNotFound
  27. }
  28. articleDTO := mapper.ConvertArticleModelToDTO(*article)
  29. // All used tags
  30. tags, err := sp.GetTagRepository().GetAllUsed(ctx.Context())
  31. if err != nil {
  32. return err
  33. }
  34. tagsDTO := mapper.ConvertTagModelsToDTO(tags)
  35. // Last articles
  36. articles, err := sp.GetArticleRepository().GetAllPreview(ctx.Context())
  37. if err != nil {
  38. return err
  39. }
  40. if len(articles) > maxArticlesCount {
  41. articles = articles[:maxArticlesCount]
  42. }
  43. renderData = fiber.Map{
  44. "headTitle": "От слона к суслику - статьи про PHP, Go, алгоритмы",
  45. "headDescription": articleDTO.MetaDescription,
  46. "headKeywords": articleDTO.MetaKeywords,
  47. "pageTitle": "Статья<br>" + articleDTO.Title,
  48. "article": articleDTO,
  49. "sidebarArticles": mapper.ConvertArticlePreviewModelsToDTO(articles),
  50. "sidebarTags": tagsDTO,
  51. }
  52. sp.GetCacheService().Set(articleCacheKey+articleReq, renderData)
  53. }
  54. return ctx.Render("article", renderData, "_layout")
  55. }
  56. }