Fork me on GitHub
#code-reviews
<
2024-02-06
>
dumrat16:02:52

Is this a reasonable idea?

;; Defines a hiccup generating function. Adds :is-hiccup = true to response map.
(defmacro defhiccup [name body]
  (let [request (gensym)]
    `(defn ~name [~request]
       (-> ~request
        (assoc :is-hiccup true)
        (assoc :body ~body)))))

;; If response map has :is-hiccup = true, convert body hiccup into html string.
(defn wrap-hiccup-body->html [handler]
  (fn [request]
    (let [response (handler request)
          body (:body response)
          response (if (:is-hiccup response)
                     (assoc response :body (str (hiccup/html body)))
                     response)]
      response)))

;; For reitit
(def hiccup->html-middleware
  {:name ::hiccup->html
   :description "Convert hiccup responses to html"
   :wrap wrap-hiccup-body->html})

(comment 
  
  (defhiccup hi-fragment
    [:div "Hi"])
  
  (hi-fragment {}) ;;=> {:is-hiccup true, :body [:div "Hi"]} 
  
  ,,)

timo09:02:15

I don't see the point in using a macro here. I guess you're doing this to keep it more compact... probably fine

👍 2
slipset11:02:24

Why not play around with Content-type headers in the response?

slipset11:02:05

(if (= (get (:headers response) "Content-type") "data/hiccup")
   ;; do your hiccup transformation and set content-type accordingly
   ;; pass through)

👍 1