Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ npm start
- Use `require('micro').json`.
- Buffers and parses the incoming body and returns it.
- Exposes an `async` function that can be run with `await`.
- Can be called multiple times, as it caches the raw request body the first time.
- `limit` is how much data is aggregated before parsing at max. Otherwise, an `Error` is thrown with `statusCode` set to `413` (see [Error Handling](#error-handling)). It can be a `Number` of bytes or [a string](https://www.npmjs.com/package/bytes) like `'1mb'`.
- If JSON parsing fails, an `Error` is thrown with `statusCode` set to `400` (see [Error Handling](#error-handling))
- Example:
Expand Down
11 changes: 10 additions & 1 deletion lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,21 @@ async function run(req, res, fn, onError) {
}
}

// maps requests to buffered raw bodies so that
// multiple calls to `json` work as expected
const rawBodyMap = new WeakMap()

async function json(req, {limit = '1mb'} = {}) {
try {
const type = req.headers['content-type']
const length = req.headers['content-length']
const encoding = typer.parse(type).parameters.charset
const str = await getRawBody(req, {limit, length, encoding})

let str = rawBodyMap.get(req)
if (!str) {
str = await getRawBody(req, {limit, length, encoding})
rawBodyMap.set(req, str)
}

try {
return JSON.parse(str)
Expand Down