Middleware helper function to format data in POST or PUT requests

@param  {Request}  req  The Request Object
@param  {Response} res  The response object
@param  {Function} next Continue past this middleware
@return {void}
431095
function(req, res, next) {
      var accData = req.user.Account
        , newData = {
          name:       req.body.name       || accData.name,
          logo:       req.body.logo       || accData.logo,
          info:       req.body.info       || accData.info,
          email:      req.body.email      || accData.email,
          themeColor: req.body.themeColor || accData.themeColor
        };

      req.body = newData;
      next();
    }
994698
function postRouter(sessions, controllers, nonObjTemplatelogLevel, req, res, next) {

    if (req.originalUrl.match(/amorphic\/xhr\?path\=/) && url.parse(req.originalUrl, true).query.form && req.method === 'POST') {
        processPost(req, res, sessions, controllers, nonObjTemplatelogLevel);
    }
    else {
        next();
    }
}
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));
}
605475
function processFileResponse(req, res, next) {
  var fileDetails = req.appformsResultPayload.data;
  if (fileDetails.stream) {
    var headers = {};
    headers["Content-Type"] = fileDetails.type;//Setting the file content type. Mime types are set by the file handler.
    headers["Content-Disposition"] = "attachment; filename=" + fileDetails.name;
    res.writeHead(200, headers);
    fileDetails.stream.pipe(res);
    fileDetails.stream.resume(); //Unpausing the stream as it was paused by the file handler
  } else {
    return next('Error getting submitted file - result: ' + JSON.stringify(fileDetails));
  }
}
1200765
function(req, res, next) {
    var data = res.data || null;
    var code = 200;
    if (_.isNumber(res.code)) {
      code = res.code;
    }
    var envelope = {
      meta: {
        code: code
      },
      data: data
    };

    // Optional paging meta
    if (res.paging) {
      envelope.meta.paging = res.paging;
    }

    // Set code and data
    res.code = code;
    if (res.code !== 204) {
      res.data = envelope;
    }

    return next();
  }
87077
function callbackMiddleware (req, res, next) {
  if (req.url.indexOf('callback') === -1) {
    next()
  } else if (req.url.indexOf('error') === -1) {
    res.status(200).jsonp({ created: true })
  } else {
    res.status(400).jsonp({ error: true })
  }
}
839515
function(request, response, next){
		if (!utils.Misc.isNullOrUndefined(request.user) || request.originalUrl == '/error' || request.originalUrl.indexOf('/error?') == 0) {
			next();
		}
		else {
			var success = encodeURIComponent(request.protocol + '://' + request.get('host') + request.originalUrl);
			response.redirect('/login?success=' + success + '&no_query=true'); //we don't want it to add any query string
		}
	}
1193671
function formatResponse (res) {
    // iterate over rows in response
    _.each(res, row => {
        // iterate over key/value pairs in row object
        _.each(row, (val, key) => {
            // convert nulls to undefined
            if (val === null) {
                row[key] = undefined
            }
        })
    })
}
734429
function responseHandler (res, next) {
  return function (err, message) {
    if (err || !message) {
      next(err);
    } else {
      res.send(message);
    }
  }
}
1109043
function putFn (req, res, next) {
    var reqPath = req.params[0];
    var destination = req.body.rename;
    debug('putFn', 'reqPath', reqPath);

    fs.rename(path.join(ramlPath, reqPath), path.join(ramlPath, destination), function (err) {
      if (err) return next(err);
      res.sendStatus(200);
    });
  }
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)
}
1131483
function destroy(req, res, next) {
  db.posts.del(req.params.post, function(err) {
    if(err) { return next(err); }
    res.json(null);
    signals.emit('post:destroy', req.params.post);
  });
}
542695
function sendText (req, res, next, data) {
  setContentType(req, res,
    ["text", "html", "text/*", "application/*"],                // allow these types
    ["json", "*/json", "+json", "application/octet-stream"]);   // don't allow these types

  util.debug("Serializing the response as a string");
  res.send(_(data).toString());
}
1226386
function doPost(options, data, callback) {
  var buffer = '';
  var req = http.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
      buffer += chunk;
    });
    res.on('end', function(err) {
      callback(err, buffer);
    });
  }).on('error', function(e) {
    callback(e);
  });

  if (data && data.length) {
    req.write(data);
  }
  req.end();
}
1124770
function reqres(res, req) {
    if (req && req._headers) {
        throw new Error('Received response object where request object was expected');
    }
    this.res = res;
    this.req = req;
    if (res) {
        if (res.$ && res.$.data) {
            this.data = res.$.data;
        }
        else {
            this.data = { error: null };
            if (!res.$) {
                res.$ = this;
            }
        }
    }
}
685256
function clone(req, res, next) {
  var cloneFormParams = {
    _id: req.params.id,
    name: req.body.name,
    userEmail: req.body.updatedBy
  };

  logger.debug("Middleware: clone form: ", {params: cloneFormParams});

  forms.cloneForm(_.extend(req.connectionOptions, cloneFormParams), formsResultHandlers(constants.resultTypes.forms, req, next));
}
406152
function sendResponse (req, res, next, dataStore) {
  return function (err, resource) {
    if (!err) {
      util.debug("%s successfully created/edited/deleted", resource.toString());
      res.swagger.lastModified = resource.modifiedOn;
    }

    // Set the response body (unless it's already been set by other middleware)
    if (err || res.body) {
      next(err);
    }
    else if (res.swagger.isCollection) {
      // Response body is the entire collection
      dataStore.getCollection(resource.collection, (err, collection) => {
        res.body = _.map(collection, "data");
        next(err);
      });
    }
    else {
      // Response body is the resource that was created/update/deleted
      res.body = resource.data;
      next();
    }
  };
}