Last active
August 29, 2015 14:07
-
-
Save ubik2/95d18f849b7b2878e4e0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
diff --git a/lib/index.js b/lib/index.js | |
index c05ed36..e4b0e07 100644 | |
--- a/lib/index.js | |
+++ b/lib/index.js | |
@@ -8,7 +8,37 @@ var auth = require("./auth"); | |
var util = require("./util"); | |
var Metadata = require('./metadata'); | |
var async = require('async'); | |
-var xmlutil = require('xml2json'); | |
+var xml2js = require('xml2js'); | |
+// optional dependency | |
+try { | |
+ var xml2json = require('xml2json'); | |
+} catch (er) { | |
+ xml2json = null; | |
+} | |
+ | |
+//utility method to convert to numbers or booleans based on value | |
+function coerceObject(obj) { | |
+ if (obj instanceof Object) { | |
+ for (var property in obj) { | |
+ if (obj.hasOwnProperty(property)) { | |
+ obj[property] = coerceObject(obj[property]); | |
+ } | |
+ } | |
+ } else if (typeof(obj) == "string") { | |
+ var _tmp = Number(obj); | |
+ if (!isNaN(_tmp)) { | |
+ return _tmp; | |
+ } | |
+ _tmp = obj.toLowerCase(); | |
+ if (_tmp == 'true') { | |
+ return true; | |
+ } else if (_tmp == "false") { | |
+ return false; | |
+ } | |
+ } | |
+ return obj; | |
+} | |
+ | |
//public api | |
exports.create = exports.load = function(opts, callback) { | |
@@ -113,10 +143,18 @@ Spreadsheet.prototype.request = function(opts, callback) { | |
var result; | |
try { | |
- result = JSON.parse(body); | |
+ result = JSON.parse(body); // older spreadsheets used a json api | |
} catch (e) { | |
try { | |
- result = JSON.parse(xmlutil.toJson(body)); | |
+ if (xml2json != null) { // xml2json is faster, but requires a native librar | |
+ result = xml2json.toJson(body, {object: true, sanitize: false, trim: false}); | |
+ } else { // xml2js is all javascript, but is slower and can run out of memory on large sets | |
+ xml2js.parseString(body, {mergeAttrs: true, charkey: '$t', explicitArray: false}, function(err, res) { | |
+ if (err) throw err; | |
+ result = res; | |
+ }); | |
+ result = coerceObject(result); // xml2js doesn't automatically coerce the datatypes | |
+ } | |
} catch (e) { | |
return callback('Bad response format (' + e + ')'); | |
} | |
diff --git a/package.json b/package.json | |
index 3b881cd..2b994b2 100644 | |
--- a/package.json | |
+++ b/package.json | |
@@ -8,6 +8,9 @@ | |
"request": "~2.21.0", | |
"google-oauth-jwt": "0.0.4", | |
"async": "~0.2.9", | |
+ "xml2js": "~0.4.4" | |
+ }, | |
+ "optionalDependencies": { | |
"xml2json": "~0.4.0" | |
}, | |
"repository": "git://github.com/jpillora/node-edit-google-spreadsheet.git" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment