Search code examples
clojurecompojureluminus

Processing multiple fields with map in Luminus/Compojure


I have this:

(defn my-page []
  (layout/render
   "page1.html" ({:articles (map
                             #(update % :field1 (fn [d] (something.... )))
                              (db/get-all-articles))})))
                            ; how can I call map again to process other fields?
                            ; (map for :field2 .... ???? how?)
                            ; (map for :field3 .... ???? how?)     

I want to preprocess other fields also. How can I properly do that? I mean, since I already have the variable :article and function map, how would I do map again for other fields such as :field2 and field3?


Solution

  • Use a threading macro:

    (def m {:field1 1
            :field2 2
            :field3 3})
    
    (-> m
      (update :field1 (fn [v1] ...))
      (update :field2 (fn [v2] ...))
      (update :field3 (fn [v3] ...)))
    

    It's equivalent to:

    (update
      (update 
        (update m :field1 (fn [v1] ...))
        (fn [v2] ...))
      (fn [v3] ...))
    

    You can enclose such logic in a function and use it to map all the articles.