wzp
2021-05-13 7d694a9113118daec5be7ac224dab46a3b20f106
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
 * Dependencies
 */
 
'use strict';
 
var csv = require('csv');
var assert = require('assert-plus');
 
///--- API
 
/**
 * Returns a plugin that will parse the HTTP request body if the
 * contentType is `text/csv` or `text/tsv`.
 *
 * @public
 * @function fieldedTextParser
 * @param    {Object}    options - an options object
 * @returns  {Function} Handler
 */
function fieldedTextParser(options) {
    assert.optionalObject(options, 'options');
 
    function parseFieldedText(req, res, next) {
        // save original body on req.rawBody and req._body
        req.rawBody = req._body = req.body;
 
        var contentType = req.getContentType();
 
        if (
            (contentType !== 'text/csv' &&
                contentType !== 'text/tsv' &&
                contentType !== 'text/tab-separated-values') ||
            !req.body
        ) {
            next();
            return;
        }
 
        var hDelimiter = req.headers['x-content-delimiter'];
        var hEscape = req.headers['x-content-escape'];
        var hQuote = req.headers['x-content-quote'];
        var hColumns = req.headers['x-content-columns'];
 
        var delimiter = contentType === 'text/tsv' ? '\t' : ',';
        delimiter = hDelimiter ? hDelimiter : delimiter;
        var escape = hEscape ? hEscape : '\\';
        var quote = hQuote ? hQuote : '"';
        var columns = hColumns ? hColumns : true;
 
        var parserOptions = {
            delimiter: delimiter,
            quote: quote,
            escape: escape,
            columns: columns
        };
 
        csv.parse(req.body, parserOptions, function parse(err, parsedBody) {
            if (err) {
                return next(err);
            }
 
            // Add an "index" property to every row
            parsedBody.forEach(function forEach(row, index) {
                row.index = index;
            });
            req.body = parsedBody;
            return next();
        });
    }
 
    return parseFieldedText;
}
 
module.exports = fieldedTextParser;