Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Always error asynchronously from parseAsync method #412

Merged
merged 1 commit into from
Sep 9, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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