UNPKG

@axway/api-builder-runtime

Version:

API Builder Runtime

68 lines (65 loc) 1.62 kB
/** * Formats the body using XML. * @param req * @param resp * @param body * @param singular * @param plural * @param callback */ exports.format = function xmlFormatter(req, resp, body, singular, plural, callback) { resp && resp.set('Content-Type', 'application/xml'); var xml = require('xml'); body = body[plural] || body[singular] || body; body = JSON.parse(JSON.stringify(body)); var key, root = {}; if (body && typeof body === 'object') { if (Array.isArray(body)) { root[plural] = []; body.forEach(function (row) { var obj = {}; var array = []; obj[singular] = array; if (row && typeof row === 'object' && !Array.isArray(row)) { Object.keys(row).forEach(function (key) { var object = {}; object[key] = row[key] !== undefined ? row[key] : ''; array.push(object); }); } else { array.push(row); } root[plural].push(obj); }); body = root; key = plural; } else { var obj = {}; var array = []; obj[singular] = array; Object.keys(body).forEach(function (key) { var object = {}; object[key] = body[key] !== undefined ? body[key] : ''; array.push(object); }); body = obj; key = singular; } } else { // it's a basic value key = singular; root[key] = [ body ]; body = root; } // add in our request attributes body[key].unshift({ _attr: { 'request-id': req && req.getId(), success: true } }); resp && resp.set('Content-Type', 'application/xml'); body = xml(body, { declaration: true, indent: '\t' }); callback(null, body); }; exports.defaultMimeType = 'application/xml';