UNPKG

@axway/api-builder-runtime

Version:

API Builder Runtime

99 lines (90 loc) 2.19 kB
var json2csv = require('json2csv'); /** * Formats the body as CSV. * @param req * @param resp * @param body * @param singular * @param plural * @param callback * @returns {*} */ exports.format = function csvFormatter(req, resp, body, singular, plural, callback) { /** * Is the var a basic value? * @param v * @returns {boolean} */ function isValue(v) { return !v || typeof v !== 'object'; } /** * is the var an object? * @param v * @returns {boolean} */ function isObject(v) { return !isValue(v) && !Array.isArray(v); } /** * is the var (arr/obj) empty * @param v * @returns {boolean} */ function isEmpty(v) { return Object.keys(v).length === 0; } resp && resp.set('Content-Type', 'text/csv'); body = body[plural] || body[singular] || body; body = JSON.parse(JSON.stringify(body)); if (isValue(body)) { // it's just a single value. return it. return callback(null, body.toString()); } if (isEmpty(body)) { return callback(null, ''); } if (isObject(body)) { body = [ body ]; } // it's now an array var cols = { value: false, object: false }; for (var i = 0; i < body.length; i++) { var row = body[i]; if (isValue(row)) { cols.value = true; } if (Array.isArray(row)) { // no support for embedded arrays in csv return callback(new Error('Cannot format embedded arrays as csv')); } if (isObject(row)) { cols.object = true; } } if (cols.object && !cols.value) { // response is made up of objects var fields = body.length && Object.keys(body[0]); if (!fields) { return callback(new Error('Cannot format as CSV')); } try { const opts = { fields, newLine: '\n' }; const parser = new json2csv.Parser(opts); const csv = parser.parse(body); return callback(null, csv); } catch (ex) { callback(ex); } // there are just values } else if (cols.object && cols.value) { // we won't format csv where there is a mix of objects and values return callback(new Error('Cannot format a mix of objects and values as CSV')); } else { // single dimensional array of values return callback(null, body.join(',')); } }; exports.defaultMimeType = 'text/csv';