Skip to content

Commit

Permalink
A few additional checks for JSON/XML parsing.
Browse files Browse the repository at this point in the history
  • Loading branch information
tomas committed Mar 5, 2014
1 parent d458ae5 commit 0f428d4
Showing 1 changed file with 17 additions and 21 deletions.
38 changes: 17 additions & 21 deletions lib/needle.js
Expand Up @@ -39,14 +39,18 @@ var debug = function(str, obj) {


var parsers = { var parsers = {
'application/json': function(data, callback) { 'application/json': function(data, callback) {
var err, str = data;
try { try {
callback(null, data && JSON.parse(data)); str = JSON.parse(data);
} catch(e) { } catch(e) {
callback(e, data); err = e;
} }
callback(err, data);
} }
}; };


parsers['text/javascript'] = parsers['application/json'];

try { try {
var xml2js = require('xml2js'); var xml2js = require('xml2js');
parsers['application/xml'] = function(data, callback) { parsers['application/xml'] = function(data, callback) {
Expand Down Expand Up @@ -319,7 +323,7 @@ var Needle = {
} }


// if there's a parser for the content type received, process it // if there's a parser for the content type received, process it
if (opts.parse && parsers[opts.content_type]) { if (opts.parse && typeof parsers[opts.content_type] == 'function') {
parsers[opts.content_type](resp.body.toString(), handle_output); parsers[opts.content_type](resp.body.toString(), handle_output);
} else { } else {
// if charset is not UTF-8 and decode option is true, transmogrify it // if charset is not UTF-8 and decode option is true, transmogrify it
Expand All @@ -343,25 +347,17 @@ exports.defaults = function(obj) {
return defaults; return defaults;
} }


exports.head = function(uri, options, callback) { 'head get'.split(' ').forEach(function(method) {
return Needle.request('HEAD', uri, null, options, callback); exports[method] = function(uri, options, callback) {
} return Needle.request(method, uri, null, options, callback);

}
exports.get = function(uri, options, callback) { })
return Needle.request('GET', uri, null, options, callback);
}

exports.post = function(uri, data, options, callback) {
return Needle.request('POST', uri, data, options, callback);
}

exports.put = function(uri, data, options, callback) {
return Needle.request('PUT', uri, data, options, callback);
}


exports.delete = function(uri, data, options, callback) { 'post put delete'.split(' ').forEach(function(method) {
return Needle.request('DELETE', uri, data, options, callback); exports[method] = function(uri, data, options, callback) {
} return Needle.request(method, uri, data, options, callback);
}
})


exports.request = function(method, uri, data, opts, callback) { exports.request = function(method, uri, data, opts, callback) {
return Needle.request(method.toUpperCase(), uri, data, opts, callback); return Needle.request(method.toUpperCase(), uri, data, opts, callback);
Expand Down

0 comments on commit 0f428d4

Please sign in to comment.