1
\$\begingroup\$

Node's HTTP library provides a handy shorthand function for GET requests. Something similar doesn't exist for POST requests. I'm trying to write one in ClojureScript that compiles to node-readable JavaScript.

In JavaScript (+ underscore.js) it would look like so:

var _ = require("underscore");
var url = require("url");
var http = require("http");

function postData (url_str, data, cb) {
   var parsed_url = url.parse(url_str);
   var options = _.extend(parsed_url, {method: "POST"});
   var req = http.request(options, cb);
   req.write(data);
   req.end();
}

postData("http://myurl:55555", "the data", function(res) {
   console.log(res.statusCode);
});

(Note: error handling should be added + passing the whole parsed_url object, extended by the method is maybe not necessary, but doesn't hurt either).

Now this should be transfered to ClojureScript. Here's an approach which technically works, however I'm asking myself if this is really the best solution:

(def url (node/require "url"))
(def http (node/require "http"))

(defn post-data [url_str data cb]
  (let [parsed_url (.parse url url_str)]
    (aset parsed_url "method" "POST")
    (let [req (.request http parsed_url cb)]
      (doto req
        (.write data)
        (.end)))))

(post-data "http://localhost:55555" "my data" #(println (.-statusCode %1)))

Does anybody have some comments/improvements for this?

\$\endgroup\$
1
\$\begingroup\$

Looks great! Some minor suggestions; pull the parsed-url aset into a doto, and that naming the request req isn't very useful. Prefer dash to underscore.

(let [parsed-url (doto (.parse url url_str)
                   (aset "method" "POST"))]
  (doto (.request http parsed-url cb)
    (.write data)
    (.end)))
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.