{"size": 2099, "ext": "js", "max_stars_repo_path": "index.js", "max_stars_repo_name": "cmd-johnson/body-parsers", "max_stars_repo_stars_event_min_datetime": "2016-01-20T06:09:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T10:45:19.000Z", "max_issues_repo_path": "index.js", "max_issues_repo_name": "cmd-johnson/body-parsers", "max_issues_repo_issues_event_min_datetime": "2015-05-30T20:43:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T16:17:50.000Z", "max_forks_repo_path": "index.js", "max_forks_repo_name": "cmd-johnson/body-parsers", "max_forks_repo_forks_event_min_datetime": "2016-04-05T18:32:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T11:09:07.000Z"}
{"max_stars_count": 35, "max_issues_count": 51, "max_forks_count": 9, "avg_line_length": 22.329787234, "max_line_length": 70, "alphanum_fraction": 0.6403049071}
'use strict'

/**
 * To do: move most of the body parsing stuff to a separate library.
 */

const get = require('raw-body')
const qs = require('querystring')

module.exports = (app) => {
  Object.keys(request).forEach((key) => {
    app.request[key] = request[key]
  })
  Object.keys(response).forEach((key) => {
    app.response[key] = response[key]
  })
  Object.keys(context).forEach((key) => {
    app.context[key] = context[key]
  })
  return app
}

const context = {}
const request = {}
const response = {}

request.json = function (limit) {
  if (!this.length) return Promise.resolve()
  return this.text(limit).then((text) => this._parse_json(text))
}

request._parse_json = function (text) {
  if (this.app.jsonStrict !== false) {
    text = text.trim()
    const first = text[0]
    if (first !== '{' && first !== '[') {
      this.ctx.throw(400, 'only json objects or arrays allowed')
    }
  }
  try {
    return JSON.parse(text)
  } catch (err) {
    this.ctx.throw(400, 'invalid json received')
  }
}

request.urlencoded = function (limit) {
  if (!this.length) return Promise.resolve()
  return this.text(limit).then((text) => this._parse_urlencoded(text))
}

request._parse_urlencoded = function (text) {
  const parse = (this.app.querystring || qs).parse
  try {
    return parse(text)
  } catch (err) {
    this.ctx.throw(400, 'invalid urlencoded received')
  }
}

request.body = function (limit) {
  switch (this.is('urlencoded', 'json')) {
    case 'json': return this.json(limit)
    case 'urlencoded': return this.urlencoded(limit)
  }
}

request.text = function (limit) {
  this.response.writeContinue()
  return get(this.req, {
    limit: limit || '100kb',
    length: this.length,
    encoding: 'utf8'
  })
}

request.buffer = function (limit) {
  this.response.writeContinue()
  return get(this.req, {
    limit: limit || '1mb',
    length: this.length
  })
}

response.writeContinue = function () {
  if (!this._checkedContinue && this.req.checkContinue) {
    this.res.writeContinue()
    this._checkedContinue = true
  }
  return this
}

context.save = require('fs-cp')
