Parse `values` for a Waterline `create` or `update` from all
request parameters.

@param  {Request} req
@return {Object}
764309
function(req, model) {

    var values = req.body.data.attributes || {};

    if (req.allParams()['id']) {
      values[model.primaryKey] = req.allParams()['id'];
    }

    return values;
  }
323022
function parse(string) {
  if (!string) {
    throw new TypeError('argument string is required')
  }

  if (typeof string === 'object') {
    // support req/res-like objects as argument
    string = getcontenttype(string)

    if (typeof string !== 'string') {
      throw new TypeError('content-type header is missing from object');
    }
  }

  if (typeof string !== 'string') {
    throw new TypeError('argument string is required to be a string')
  }

  var index = string.indexOf(';')
  var type = index !== -1
    ? string.substr(0, index).trim()
    : string.trim()

  if (!typeRegExp.test(type)) {
    throw new TypeError('invalid media type')
  }

  var key
  var match
  var obj = new ContentType(type.toLowerCase())
  var value

  paramRegExp.lastIndex = index

  while (match = paramRegExp.exec(string)) {
    if (match.index !== index) {
      throw new TypeError('invalid parameter format')
    }

    index += match[0].length
    key = match[1].toLowerCase()
    value = match[2]

    if (value[0] === '"') {
      // remove quotes and escapes
      value = value
        .substr(1, value.length - 2)
        .replace(qescRegExp, '$1')
    }

    obj.parameters[key] = value
  }

  if (index !== -1 && index !== string.length) {
    throw new TypeError('invalid parameter format')
  }

  return obj
}
1218553
function extendHttpRequest(req) {
    req = req || express.request;

    /**
     * get param value from path-variable or query or body or headers.
     * @param {string} paramName
     * @param {*} [fallback]
     * @returns {*}
     */
    req.anyParam = function (paramName, fallback) {
        return (this.params && this.params[paramName]) || // path-variable
            (this.query && this.query[paramName]) ||
            (this.body && this.body[paramName]) ||
            (this.get && this.get(paramName)) || // header
            fallback;
    };

    /**
     * get string param from http request.
     *
     * @param {String} paramName
     * @param {String} [fallback]
     * @returns {String} param value
     * @throws {errors.BadRequest} no string param acquired and no fallback provided
     * @memberOf {express.request}
     */
    req.strParam = function (paramName, fallback) {
        var paramValue = this.anyParam(paramName);
        if (paramValue !== undefined) {
            return paramValue;
        }
        if (fallback !== undefined) {
            return fallback;
        }
        throw new errors.BadRequest('param_required:' + paramName);
    };

    /**
     * get integer param from http request.
     *
     * @param {String} paramName
     * @param {Number} [fallback]
     * @returns {Number} param value
     * @throws {errors.BadRequest} no integer param acquired and no fallback provided
     * @memberOf {express.request}
     */
    req.intParam = function (paramName, fallback) {
        var paramValue = utils.toInt(this.anyParam(paramName), fallback);
        if (paramValue !== undefined) {
            return paramValue;
        }
        if (fallback !== undefined) {
            return fallback;
        }
        throw new errors.BadRequest('int_param_required:' + paramName);
    };

    /**
     * get number(float) param from http request.
     *
     * @param {String} paramName
     * @param {Number} [fallback]
     * @returns {Number} param value
     * @throws {errors.BadRequest} no number param acquired and no fallback provided
     * @memberOf {express.request}
     */
    req.numberParam = function (paramName, fallback) {
        var paramValue = utils.toNumber(this.anyParam(paramName));
        if (paramValue !== undefined) {
            return paramValue;
        }
        if (fallback !== undefined) {
            return fallback;
        }
        throw new errors.BadRequest('number_param_required:' + paramName);
    };

    /**
     * get boolean param from http request.
     *
     * @param {String} paramName
     * @returns {Boolean} [fallback]
     * @returns {Boolean} param value
     * @throws {errors.BadRequest} no boolean param acquired and no fallback provided
     * @memberOf {express.request}
     */
    req.boolParam = function (paramName, fallback) {
        var paramValue = utils.toBoolean(this.anyParam(paramName));
        if (paramValue !== undefined) {
            return paramValue;
        }
        if (fallback !== undefined) {
            return fallback;
        }
        throw new errors.BadRequest('bool_param_required:' + paramName);
    };

    /**
     * get date param from http request.
     *
     * @param {String} paramName
     * @param {Date} [fallback]
     * @returns {Date} param value
     * @throws {errors.BadRequest} no date param acquired and no fallback provided
     * @memberOf {express.request}
     */
    req.dateParam = function (paramName, fallback) {
        var paramValue = Date.parse(this.anyParam(paramName));
        if (!isNaN(paramValue)) {
            return new Date(paramValue);
        }
        if (fallback !== undefined) {
            return fallback;
        }
        throw new errors.BadRequest('date_param_required:' + paramName);
    };

    /**
     * collect params from http request.
     *
     * @param {Array.<String>} paramNames
     * @returns {Object.<String,String>}
     */
    req.collectParams = function (paramNames) {
        var self = this;
        return paramNames.reduce(function (params, paramName) {
            var paramValue = self.strParam(paramName);
            if (paramValue) {
                params[paramName] = paramValue.trim();
            }
            return params;
        }, {});
    };
}
796209
function _extract(req, param){

    var ret = [];

    // Note: no route parameter possible with lists(?).

    // Try the get space.
    if( req && req.query && typeof(req.query[param]) !== 'undefined' ){
	//console.log('as query');

	// Input as list, remove dupes.
	var paccs = req.query[param];
	if( paccs && ! us.isArray(paccs) ){
	    paccs = [paccs];
	}
	ret = us.uniq(paccs);
    }

    // Otherwise, try the body space.
    if( us.isEmpty(ret) ){

	var decoded_body = req.body || {};
	if( decoded_body && ! us.isEmpty(decoded_body) && decoded_body[param] ){
	    //console.log('as body');

	    // Input as list, remove dupes.
	    var baccs = decoded_body[param];
	    //console.log('decoded_body', decoded_body);
	    //console.log('baccs', baccs);
	    if( baccs && ! us.isArray(baccs) ){
		baccs = [baccs];
	    }
	    ret = us.uniq(baccs);
	}
    }

    return ret;
}
851677
function(rel, key, val, callback) {
    if (typeof key == 'function') {
      callback = key;
      key = val = undefined;
    }

    if (Array.isArray(rel)) {
      var txn = this._safeBatch();
      var args = [key, val];
      async.map(rel, naan.ecurry(txn.rel.update, args, [1, 2]), callback);
      return this._safeBatchCommit(txn);
    }

    var id = this._getId(rel);

    if (!this._isValidId(id)) {
      return callback(new Error("Invalid ID"));
    }

    var endpoint = util.format('%s/properties', this._relRoot(id));
    if (key) endpoint += '/' + key;

    var op = this.operation(endpoint, 'PUT', key ? val : rel.properties);
    this.call(op, function(err) {
      callback(err);
    });
  }
395275
function parseDeleteRequest(req){
  var reqObj = {};
  reqObj.originalUrl = req.originalUrl;
  reqObj.uid = req.params.guid;
  reqObj.env =req.params.environment;
  reqObj.domain = req.params.domain;
  reqObj._id = req.params.id;
  return reqObj;
}
349055
function parseOptions(req, options) {
  if (options.query) {
    req.qs = options.query
  }
  if (options.body) {
    req.json = options.body
  }
  if (options.hasOwnProperty('encoding')) {
    req.encoding = options.encoding
  }
  if (options.headers) {
    for (let key in options.headers) {
      req.headers[key] = options.headers[key]
    }
  }
  return req
}
615268
function handler(req, res) {

  var parsedUrl = url.parse(req.url)
  var callback = qs.parse(parsedUrl.query).callback
  var filename = decodeURI(parsedUrl.path.substr(1).split('?')[0])
  var basename = path.basename(filename.split('?')[0])
  var extname = path.extname(basename)
  var response = reswrap(res);
  var notfound = function() {
    response.writeHead(404, 'text').end('');
  };

  if (req.method === 'GET' && parsedUrl.pathname === '/jsonp-request') {
    if (!!exitCountdown) {
      exitCountdown.restart();
    }

    response
      .writeHead(200, 'js')
      .end(callback +'('+ R.get('stamp') +')');

    return;
  }

  var serve;
  if (/^\/template/.test(parsedUrl.pathname)) {
    serve = check(join(__dirname, '..', filename))
  } else if (/^\/node_modules/.test(parsedUrl.pathname)) {
    serve = check(join(__dirname, '..', filename))
  }
  if (serve) {
    serve.pass(function(name, type) {
      response
        .writeHead(200, extname.substr(1))
        .pipeWith(fs.createReadStream(
          path.resolve(name)
        ))
    }).fail(notfound);
    return;
  }

  if (/^\.(md|mkd|markdown|html)$/.test(extname)) {
    check(filename)
      .pass(function() {
        response
          .writeHead(200, 'html')
          .end(template.render({
            title: basename,
            highlight: R.get('highlight') || 'default',
            theme: getTheme(R.get('css')),
            width: R.get('width'),
            body: parser.parse(read(path.resolve(filename)))
          }));
      }).fail(notfound);

    return;
  }

  // Image or some other resources.
  check(filename)
    .pass(function(name) {
      response
        .writeHead(200, name)
        .pipeWith(fs.createReadStream(name));
    }).fail(notfound)
}
1168836
function(req, res) {
            var updateJson = {};
            var updateSelector = {};

            //Request database structure
            lastQry = connection.query('SHOW COLUMNS FROM ??', req.params.table , function (err, columns) {
                if (err) return sendError(res,err.code);

                //Check if the request is provided an select value
                if (typeof req.params.id === "undefined") {
                    return sendError(res,'Please specify an selector value for the fields ');
                } else {
                    updateSelector.value = req.params.id;
                    updateSelector.field = findPrim(columns,req.query[settings.paramPrefix + 'field']);
                }

                //If the user only wants to update files
                if( Object.keys(req.body).length == 0) {
                    req.body = req.files;
                }
                var value;
                var iterator = function (i) {
                    if (i >= columns.length || (typeof req.body.length === "undefined" && typeof req.files.length !== "undefined")) {
                        if(JSON.stringify(updateJson) !== '{}') {
                            updateIntoDB();
                        } else {
                            return sendError(res,'No Data received!');
                        }
                        return;
                    }
                    var dbField = columns[i];
                    var field = dbField.Field;
                    //Check if the current checked field is set
                    if(typeof req.body[field] !== "undefined" || (dbField.Default == 'FILE' && typeof req.files[field] !== "undefined") ) {
                        //First check if the field is required
                        if(dbField.Null == 'NO' && dbField.Extra != 'auto_increment') {
                            value = checkIfSentvaluesAreSufficient(req,dbField);
                            if(value !== false) {
                                updateJson[field] = value;
                                iterator(i + 1);
                            } else {
                                return sendError(res,"Not all 'NOT NULL' fields are filled ("+ field +" is missing)");
                            }
                        }  else {
                            //Check for not required fields
                            //Skip auto_incremented fields
                            if(dbField.Extra === 'auto_increment') {
                                iterator(i + 1);
                            } else {
                                //Check if the field was provided by the client
                                var defined = false;
                                if(dbField.Default == "FILE") {
                                    if(req.files.hasOwnProperty(dbField.Field)) {
                                        defined = true;
                                    }
                                } else {
                                    if(typeof req.body[field] !== "undefined") {
                                        defined = true;
                                    }
                                }

                                //If it was provided, check if the values are okay
                                if(defined) {
                                    value = checkIfSentvaluesAreSufficient(req,dbField);
                                    if(value !== false) {
                                        updateJson[field] = value;
                                        iterator(i + 1);
                                    } else {
                                        if(dbField.Default == "FILE") {
                                            return sendError(res, 'Value for field ' + field + ' is not sufficient. Either the file is to large or an other error occured');
                                        } else {
                                            return sendError(res, 'Value for field ' + field + ' is not sufficient. Expecting ' + dbField.Type + ' but got ' + typeof req.body[field]);
                                        }
                                    }
                                } else {
                                    //If not, don't mind
                                    iterator(i + 1);
                                }
                            }
                        }
                    } else {
                        iterator(i + 1);
                    }
                };

                iterator(0); //start the async "for" loop

                function updateIntoDB() {
                    //Yaaay, alle Tests bestanden gogo, insert!
                    lastQry = connection.query('UPDATE ?? SET ? WHERE ?? = ?', [req.params.table , updateJson, updateSelector.field, updateSelector.value] , function (err) {
                        if (err) return sendError(res,err.code);
                        sendSuccessAnswer(req.params.table , res, req.params.id, updateSelector.field);

                    });
                }
            });
        }
461508
function parseUpdateAlertRequest(req){
  var reqObj = {};
  reqObj.originalUrl = req.originalUrl;
  reqObj.alertName = req.body.alertName;
  reqObj.emails = req.body.emails.split(',');
  reqObj.eventCategories = req.body.eventCategories.split(',');
  reqObj.eventNames = req.body.eventNames.split(',');
  reqObj.eventSeverities = req.body.eventSeverities.split(',');
  reqObj.uid = req.body.uid;
  reqObj.env = req.body.env;
  reqObj.alertEnabled = req.body.enabled;
  reqObj._id = req.params.id;
  reqObj.domain = req.params.domain;
  return reqObj;
}
766710
function wrapReplEval(replServer) {
  const defaultEval = replServer.eval;

  return function(code, context, file, cb) {
    return defaultEval.call(this, code, context, file, (err, result) => {
      if (!result || !result.then) {
        return cb(err, result);
      }

      result.then(resolved => {
        resolvePromises(result, resolved);
        cb(null, resolved);
      }).catch(err => {
        resolvePromises(result, err);

        console.log('\x1b[31m' + '[Promise Rejection]' + '\x1b[0m');
        if (err && err.message) {
          console.log('\x1b[31m' + err.message + '\x1b[0m');
        }

        // Application errors are not REPL errors
        cb(null, err);
      });
    });

    function resolvePromises(promise, resolved) {
      Object.keys(context).forEach(key => {
        // Replace any promise handles in the REPL context with the resolved promise
        if (context[key] === promise) {
          context[key] = resolved;
        }
      });
    }
  };
}
1108586
function createMiddleware(options) {
  /**
   * Express middleware handling raw content requests
   *
   * @param {Request} req Request object
   * @param {Response} res Response object
   * @param {callback} next next middleware in chain
   */
  return async (req, res, next) => {
    const { owner } = req.params;
    const repoName = req.params.repo;
    let refName = req.params.ref;
    let fpath = req.params[0];

    const repPath = resolveRepositoryPath(options, owner, repoName);

    // issue: #53: handle branch names containing '/' (e.g. 'foo/bar')
    const parsed = await determineRefPathName(repPath, `${req.params.ref}/${req.params[0]}`);
    if (parsed) {
      refName = parsed.ref;
      fpath = parsed.pathName;
    }

    // issue #247: lenient handling of redundant leading slashes in path
    while (fpath.length && fpath[0] === '/') {
      // trim leading slash
      fpath = fpath.substr(1);
    }

    // project-helix/#187: serve modified content only if the requested ref is currently checked out
    isCheckedOut(repPath, refName)
      .then(serveUncommitted => resolveBlob(repPath, refName, fpath, serveUncommitted))
      .then((oid) => {
        const mimeType = mime.getType(fpath) || 'text/plain';
        res.writeHead(200, {
          'Content-Type': mimeType,
          ETag: oid,
          // TODO: review cache-control header
          'Cache-Control': 'max-age=0, private, must-revalidate',
        });
        createBlobReadStream(repPath, oid)
          .then(stream => stream.pipe(res));
      })
      .catch((err) => {
        // TODO: use generic errors
        if (err.code === 'TreeOrBlobNotFoundError' || err.code === 'ResolveRefError') {
          options.logger.debug(`[rawHandler] resource not found: ${err.message}`);
          res.status(404).send('not found.');
        } else {
          options.logger.debug(`[rawHandler] code: ${err.code} message: ${err.message} stack: ${err.stack}`);
          next(err);
        }
      });
  };
}
505308
function create(req, res, next) {
  var options = req.connectionOptions;
  req.user = req.user || {};
  var params = {
    userEmail: req.user.email || req.body.updatedBy
  };

  options = _.extend(options, params);

  logger.debug("Middleware: create form: ", {options: options});

  forms.updateForm(options, req.body, formsResultHandlers(constants.resultTypes.forms, req, next));
}
124653
function(req){
    var params = req.params.all();
    _.merge(params, req.headers);
    return _.merge(params, req.query);
  }
9702
function parseurl (req) {
  var url = req.url

  if (url === undefined) {
    // URL is undefined
    return undefined
  }

  var parsed = req._parsedUrl

  if (fresh(url, parsed)) {
    // Return cached URL parse
    return parsed
  }

  // Parse the URL
  parsed = fastparse(url)
  parsed._raw = url

  return (req._parsedUrl = parsed)
}
437288
function parseUrlParams(params) {
    let qs = '';
    let i = 0;
    each(params, (val, key) => {
        if (i > 0) {
            qs += '&amp;';
        }
        qs += key + '=' + val;
        i += 1;
    })
    return qs;
}
690058
function(req, requiredParams) {
      // Find all missing parameters
      var missingParams = [];
      _.forEach(requiredParams, function(requiredParam) {
        if (
          Mixins.isNullOrUndefined(req.params && req.params[requiredParam]) &&
          Mixins.isNullOrUndefined(req.query && req.query[requiredParam]) &&
          Mixins.isNullOrUndefined(req.body && req.body[requiredParam])
        ) {
          missingParams.push(requiredParam);
        }
      });
      return missingParams;
    }