article_delete.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package admin
  2. import (
  3. "context"
  4. "git.dmitriygnatenko.ru/dima/go-common/logger"
  5. "github.com/gofiber/fiber/v2"
  6. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/helpers/request"
  7. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/services/handler"
  8. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/services/i18n"
  9. )
  10. type articleDeletePage struct {
  11. tm TransactionManager
  12. articleRepository ArticleRepository
  13. articleTagRepository ArticleTagRepository
  14. cacheService CacheService
  15. }
  16. func NewArticleDeletePageHandler(
  17. tm TransactionManager,
  18. articleRepository ArticleRepository,
  19. articleTagRepository ArticleTagRepository,
  20. cacheService CacheService,
  21. ) fiber.Handler {
  22. h := articleDeletePage{
  23. tm: tm,
  24. articleRepository: articleRepository,
  25. articleTagRepository: articleTagRepository,
  26. cacheService: cacheService,
  27. }
  28. return h.handler()
  29. }
  30. func (h articleDeletePage) handler() fiber.Handler {
  31. return func(fctx *fiber.Ctx) error {
  32. ctx := fctx.Context()
  33. lang := i18n.LanguageFromContext(fctx)
  34. id, err := request.ConvertToUint64(fctx, "id")
  35. if err != nil {
  36. logger.Error(ctx, err.Error())
  37. return err
  38. }
  39. article, err := h.articleRepository.GetByID(ctx, id)
  40. if err != nil {
  41. logger.Error(ctx, err.Error())
  42. return err
  43. }
  44. if fctx.Method() == fiber.MethodPost {
  45. err = h.tm.ReadCommitted(ctx, func(ctx context.Context) error {
  46. txErr := h.articleTagRepository.DeleteByArticleID(ctx, id)
  47. if txErr != nil {
  48. return txErr
  49. }
  50. txErr = h.articleRepository.Delete(ctx, id)
  51. if txErr != nil {
  52. return txErr
  53. }
  54. return nil
  55. })
  56. if err != nil {
  57. logger.Error(ctx, err.Error())
  58. return err
  59. }
  60. h.cacheService.Delete(handler.ArticleCacheKey + string(lang) + article.URL)
  61. return fctx.Redirect("/admin")
  62. }
  63. return fctx.Render("admin/article_delete", fiber.Map{
  64. "article": article.Title,
  65. "section": "article",
  66. }, "admin/_layout")
  67. }
  68. }