body-parser-csv
Version:
CSV parser middleware for express.js
51 lines • 1.66 kB
JavaScript
;
const CSVParser_1 = require("./CSVParser");
const DEFAULT_TYPES = ["text/csv"];
module.exports = (bodyParser) => {
if (bodyParser.csv) {
// We already setup the CSV parser.
// End early.
return;
}
/// CSV parsing middleware
const csv = (options) => {
options = options || {};
options.type = options.type || DEFAULT_TYPES;
if (!Array.isArray(options.type)) {
options.type = [options.type];
}
const textParser = bodyParser.text(options);
const csvParser = (req, res, next) => {
// First, run the body through the text parser.
textParser(req, res, (err) => {
if (err) {
return next(err);
}
if (typeof req.body !== "string") {
return next();
}
// Then, parse CSV.
const parser = new CSVParser_1.CSVParser(options.csvParseOptions);
parser.parse(req.body)
.then((parsed) => {
req.body = parsed || req.body;
next();
})
.catch((error) => {
error.status = 400; // TODO: use real error status
return next(error);
});
});
};
return csvParser;
};
// Finally add the `csv` function to the bodyParser.
Object.defineProperty(bodyParser, "csv", {
configurable: true,
enumerable: true,
get() {
return csv;
},
});
};
//# sourceMappingURL=index.js.map