How to get JSON mail data in Noir

A back, Chris Granger published this middleware to get JSON hashes in defpage parameters under an umbrella "base" element.

(defn backbone [handler] (fn [req] (let [neue (if (= "application/json" (get-in req [:headers "content-type"])) (update-in req [:params] assoc :backbone (json/parse-string (slurp (:body req)) true)) req)] (handler neue)))) 

How can I change this code so that JSON elements are displayed as top-level parameters in defpage; those. to get rid of an umbrella: the spine?

+4
source share
3 answers

There are two things you can do. One option is to replace the value :params with the map obtained after parsing the JSON. To do this, simply map the new map to the key :params .

 (assoc req [:params] (json/parse-string (slurp (:body req)) true)) 

Another option (as @dAni suggests) is to combine the values ​​of the parsed JSON so that the existing values ​​in the map :params not overridden. The reason you need to use partial instead of just using merge here is because the final map is the combined result of the maps from left to right. Your solution works if you want the values ​​from the JSON map to take precedence.

 (update-in req [:params] (partial merge (json/parse-string (slurp (:body req)) true))) 
+3
source

Got it. assoc only works for one element, so you need to put everything under an umbrella :backbone . To insert all JSON elements in parameters, you must use merge . Therefore, change the 4th line to:

 (update-in req [:params] merge (json/parse-string (slurp (:body req)) true)) 
0
source

If you don't mind pulling another dependency, you can use the ring-middleware library .

Instruction:

  • Add [ring-middleware-format "0.1.1"] to your project.clj

  • and then in server.clj , add the following code:

the code:

 (:require [ring.middleware.format-params :as format-params]) (server/add-middleware format-params/wrap-json-params) (defn -main [& m] ; Start the server... ) 

Now any incoming JSON will be available for use as a POSTdata form.

-1
source

Source: https://habr.com/ru/post/1413011/


All Articles