all files / modules/middleware/ params.js

85% Statements 17/20
62.5% Branches 5/8
100% Functions 4/4
85% Lines 17/20
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                                                                            
const objectAssign = require("object-assign");
const mach = require("../index");
const MaxLengthExceededError = require("../utils/MaxLengthExceededError");
const {is} = require("ramda");
mach.extend(
  require("../extensions/server")
);
 
/**
 * Automatically parses all request parameters and stores them in conn.params.
 * This is the union of all GET (query string) and POST (content) parameters,
 * such that all POST parameters with the same name take precedence.
 *
 * Valid options are:
 *
 * - maxLength          The maximum length (in bytes) of the request content
 *
 * If the maximum allowed length is exceeded, this middleware returns a
 * 413 Request Entity Too Large response.
 *
 * Note: This middleware parses all request parameters for all downstream apps. If
 * you'd prefer to only do this work on some requests and not all, you can use
 * conn.getParams inside your app instead.
 */
function parseParams(app, options) {
    options = options || {};
 
    Iif (is(Number, options)) {
        options = {maxLength: options};
    }
 
    const maxLength = options.maxLength;
 
    return function (conn) {
        return conn.getParams(maxLength).then(function (params) {
            Iif (conn.params) {
        // Route params take precedence over content params.
                conn.params = objectAssign(params, conn.params);
            } else {
                conn.params = params;
            }
 
            return conn.call(app);
        }, function (error) {
            Eif (is(MaxLengthExceededError, error)) {
                return conn.text(413, "Request Entity Too Large");
            }
 
            throw error;
        });
    };
}
 
module.exports = parseParams;