Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question

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)))
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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