Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

A few additional checks for JSON/XML parsing.

  • Loading branch information...
commit 0f428d408c60d99e159f5dba9283aa3f20819bb5 1 parent d458ae5
@tomas authored
Showing with 17 additions and 21 deletions.
  1. +17 −21 lib/needle.js
View
38 lib/needle.js
@@ -39,14 +39,18 @@ var debug = function(str, obj) {
var parsers = {
'application/json': function(data, callback) {
+ var err, str = data;
try {
- callback(null, data && JSON.parse(data));
+ str = JSON.parse(data);
} catch(e) {
- callback(e, data);
+ err = e;
}
+ callback(err, data);
}
};
+parsers['text/javascript'] = parsers['application/json'];
+
try {
var xml2js = require('xml2js');
parsers['application/xml'] = function(data, callback) {
@@ -319,7 +323,7 @@ var Needle = {
}
// 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);
} else {
// if charset is not UTF-8 and decode option is true, transmogrify it
@@ -343,25 +347,17 @@ exports.defaults = function(obj) {
return defaults;
}
-exports.head = function(uri, options, callback) {
- return Needle.request('HEAD', 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);
-}
+'head get'.split(' ').forEach(function(method) {
+ exports[method] = function(uri, options, callback) {
+ return Needle.request(method, uri, null, options, callback);
+ }
+})
-exports.delete = function(uri, data, options, callback) {
- return Needle.request('DELETE', uri, data, options, callback);
-}
+'post put delete'.split(' ').forEach(function(method) {
+ exports[method] = function(uri, data, options, callback) {
+ return Needle.request(method, uri, data, options, callback);
+ }
+})
exports.request = function(method, uri, data, opts, callback) {
return Needle.request(method.toUpperCase(), uri, data, opts, callback);
Please sign in to comment.
Something went wrong with that request. Please try again.