diff --git a/lib/json2csv.js b/lib/json2csv.js index 0a09e615..4d57b4ce 100644 --- a/lib/json2csv.js +++ b/lib/json2csv.js @@ -12,22 +12,26 @@ module.exports.Transform = JSON2CSVTransform; // Convenience method to keep the API similar to version 3.X module.exports.parse = (data, opts) => new JSON2CSVParser(opts).parse(data); module.exports.parseAsync = (data, opts, transformOpts) => { - if (!(data instanceof Readable)) { - transformOpts = Object.assign({}, transformOpts, { objectMode: true }); - } + try { + if (!(data instanceof Readable)) { + transformOpts = Object.assign({}, transformOpts, { objectMode: true }); + } - const asyncParser = new JSON2CSVAsyncParser(opts, transformOpts); - const promise = asyncParser.promise(); + const asyncParser = new JSON2CSVAsyncParser(opts, transformOpts); + const promise = asyncParser.promise(); - if (Array.isArray(data)) { - data.forEach(item => asyncParser.input.push(item)); - asyncParser.input.push(null); - } else if (data instanceof Readable) { - asyncParser.fromInput(data); - } else { - asyncParser.input.push(data); - asyncParser.input.push(null); - } + if (Array.isArray(data)) { + data.forEach(item => asyncParser.input.push(item)); + asyncParser.input.push(null); + } else if (data instanceof Readable) { + asyncParser.fromInput(data); + } else { + asyncParser.input.push(data); + asyncParser.input.push(null); + } - return promise; + return promise; + } catch (err) { + return Promise.reject(err); + } }; diff --git a/test/JSON2CSVAsyncParser.js b/test/JSON2CSVAsyncParser.js index db0cff73..ef8f802d 100644 --- a/test/JSON2CSVAsyncParser.js +++ b/test/JSON2CSVAsyncParser.js @@ -4,6 +4,17 @@ const { Readable, Transform, Writable } = require('stream'); const { AsyncParser, parseAsync } = require('../lib/json2csv'); module.exports = (testRunner, jsonFixtures, csvFixtures, inMemoryJsonFixtures) => { + testRunner.add('should should error async if invalid opts are passed using parseAsync method', (t) => { + const opts = { + fields: [undefined] + }; + + parseAsync(inMemoryJsonFixtures.default, opts) + .then(() => t.notOk(true)) + .catch(err => t.ok(true, err.message)) + .then(() => t.end()); + }); + testRunner.add('should parse in-memory json array to csv, infer the fields automatically and not modify the opts passed using parseAsync method', (t) => { const opts = { fields: ['carModel', 'price', 'color', 'transmission']