Skip to content

Commit

Permalink
fix: Always error asynchronously from parseAsync method (#412)
Browse files Browse the repository at this point in the history
  • Loading branch information
juanjoDiaz authored and knownasilya committed Sep 9, 2019
1 parent d5566f7 commit 16cc044
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 15 deletions.
34 changes: 19 additions & 15 deletions lib/json2csv.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
};
11 changes: 11 additions & 0 deletions test/JSON2CSVAsyncParser.js
Original file line number Diff line number Diff line change
Expand Up @@ -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']
Expand Down

0 comments on commit 16cc044

Please sign in to comment.