/components/comment/src/clojure/realworld/comment/core.clj

https://github.com/furkan3ayraktar/clojure-polylith-realworld-example-app · Clojure · 45 lines · 41 code · 4 blank · 0 comment · 5 complexity · b85817956bff006db59f3a94c48f356c MD5 · raw file

  1. (ns clojure.realworld.comment.core
  2. (:require [clj-time.core :as t]
  3. [clojure.realworld.article.interface :as article]
  4. [clojure.realworld.comment.store :as store]
  5. [clojure.realworld.profile.interface :as profile]))
  6. (defn comment->visible-comment [auth-user comment]
  7. (let [user-id (:userId comment)
  8. [_ author] (profile/fetch-profile auth-user user-id)]
  9. (-> comment
  10. (dissoc :userId :articleId)
  11. (assoc :author (:profile author)))))
  12. (defn article-comments [auth-user slug]
  13. (let [[ok? {:keys [article]}] (article/article auth-user slug)]
  14. (if ok?
  15. (let [article-id (:id article)
  16. comments (store/comments article-id)
  17. res (mapv #(comment->visible-comment auth-user %) comments)]
  18. [true {:comments res}])
  19. [false {:errors {:slug ["Cannot find an article with given slug."]}}])))
  20. (defn add-comment! [auth-user slug {:keys [body]}]
  21. (let [[ok? {:keys [article]}] (article/article auth-user slug)]
  22. (if ok?
  23. (let [now (t/now)
  24. comment {:body body
  25. :articleId (:id article)
  26. :userId (:id auth-user)
  27. :createdAt now
  28. :updatedAt now}
  29. comment-id (store/add-comment! comment)]
  30. (if comment-id
  31. (let [added-comment (store/find-by-id comment-id)
  32. res (comment->visible-comment auth-user added-comment)]
  33. [true {:comment res}])
  34. [false {:errors {:other ["Cannot insert comment into db."]}}]))
  35. [false {:errors {:slug ["Cannot find an article with given slug."]}}])))
  36. (defn delete-comment! [auth-user id]
  37. (if-let [comment (store/find-by-id id)]
  38. (if (= (:id auth-user) (:userId comment))
  39. [true (store/delete-comment! id)]
  40. [false {:errors {:authorization ["You need to be author of this comment to delete it."]}}])
  41. [false {:errors {:id ["Cannot find a comment with given id."]}}]))