Skip to content

Instantly share code, notes, and snippets.

@ErisDS
Created May 11, 2017 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ErisDS/82875e6284e08b202a5c7e3721e4645b to your computer and use it in GitHub Desktop.
Save ErisDS/82875e6284e08b202a5c7e3721e4645b to your computer and use it in GitHub Desktop.
Convert Recurly XML to JSON, with promises.
'use strict';
const _ = require('lodash');
const Promise = require('bluebird');
const debug = require('ghost-ignition').debug('xml2json');
const xmlParseOptions = {
explicitArray: false
};
const parser = new require('xml2js').Parser(xmlParseOptions);
const convertableTypes = ['integer', 'datetime', 'array'];
function doConvert(obj, name) {
// For each property on this object, convert the values
_.each(obj, (value, key) => {
// First, convert nil values to null
if (value.$ && value.$.nil === 'true') {
obj[key] = null;
}
// Second, any non-nil typed values can be converted
if (value.$ && value.$.type && convertableTypes.indexOf(value.$.type) === -1) {
// We don't know this type!
debug('NOT converting', value.$.type, 'for', key, 'value', value._);
// Simple types like integer and datetime have a value._
} else if (value.$ && value.$.type && value._) {
if (value.$.type === 'integer') {
obj[key] = parseInt(value._, 10);
}
if (value.$.type === 'datetime') {
obj[key] = Date.parse(value._);
}
// Array is a more complex type
} else if (value.$ && value.$.type === 'array') {
// We don't need the type anymore
delete value.$;
// What is left is a single key, which points to an array
// We need to convert the values fo each item in that array
_.each(_.values(value)[0], doConvert);
}
});
}
function recurlyToJSON(xml) {
const event = Object.keys(xml)[0];
const data = xml[event];
debug('converting recurly object to real json');
// Recurly returns one or more top-level objects
// Each object needs each property to be converted
_.each(data, doConvert);
debug('done converting');
return {
event: event,
data: data
};
}
module.exports = function xmlToJson(xmlString) {
return new Promise(function (resolve, reject) {
parser.parseString(xmlString, function(err, xml) {
if (err) {
return reject(err);
}
return resolve(recurlyToJSON(xml));
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment