{"size": 790, "ext": "js", "max_stars_repo_path": "lib/middleware.js", "max_stars_repo_name": "NeuraLegion/multer", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/middleware.js", "max_issues_repo_name": "NeuraLegion/multer", "max_issues_repo_issues_event_min_datetime": "2020-03-09T15:06:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-09T17:09:54.000Z", "max_forks_repo_path": "lib/middleware.js", "max_forks_repo_name": "NeuraLegion/multer", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": 3, "max_forks_count": null, "avg_line_length": 27.2413793103, "max_line_length": 84, "alphanum_fraction": 0.7037974684}
const is = require('type-is')
const appendField = require('append-field')
const { createFileAppender } = require('./file-appender')
const readBody = require('./read-body')

const handleRequest = async (setup, req) => {
  const options = setup()
  const result = await readBody(req, options.limits, options.fileFilter)

  req.body = Object.create(null)

  for (const field of result.fields) {
    appendField(req.body, field.key, field.value)
  }

  const fileAppender = createFileAppender(options.fileStrategy, req, options.fields)

  for (const file of result.files) {
    fileAppender.append(file)
  }
}

const createMiddleware = setup => (req, res, next) => {
  if (!is(req, ['multipart'])) return next()
  handleRequest(setup, req).then(next, next)
}

module.exports = createMiddleware
