Skip to content

Commit b89581a

Browse files
authored
feat: Re-create the module with TypeScript (#152)
* refactor: imporve the return type for shouldParseBodyAs method * test: coverage 100% * feat: support the already parsed body * feat: prevent runtime problems * feat: add patchNode option to support patching ctx.req.body * feat: add parsedMethods option to parse only the passed ones * feat: support extra value under the content-type + use async/await over done in testing
1 parent 5678a79 commit b89581a

21 files changed

+1146
-672
lines changed

.github/workflows/ci.yml

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
name: Continuous Integration
2+
3+
on:
4+
- push
5+
- pull_request
6+
7+
jobs:
8+
ci:
9+
runs-on: ubuntu-latest
10+
strategy:
11+
matrix:
12+
node-version:
13+
- 16
14+
- 18
15+
- 20
16+
steps:
17+
- uses: actions/checkout@v3
18+
- name: Use Node.js ${{ matrix.node-version }}
19+
uses: actions/setup-node@v3
20+
- name: Install dependencies
21+
run: yarn install
22+
- name: Check linter
23+
run: yarn lint
24+
- name: Run tests
25+
run: yarn test-ci

.github/workflows/nodejs.yml

-15
This file was deleted.

.gitignore

+4
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,10 @@ npm-debug.log
1616
yarn-debug.log
1717
yarn-error.log
1818

19+
# Build #
20+
###################
21+
dist
22+
build
1923

2024
# NYC #
2125
###################

.npmrc

-1
This file was deleted.

.xo-config.json

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
{
2+
"prettier": true,
3+
"space": true,
4+
"extends": [
5+
"xo-lass"
6+
],
7+
"rules": {
8+
"node/no-deprecated-api": "off",
9+
"no-unused-vars": "off",
10+
"no-prototype-builtins": "off",
11+
"prefer-rest-params": "off",
12+
"n/prefer-global/process": "off",
13+
"@typescript-eslint/restrict-template-expressions": "off",
14+
"@typescript-eslint/naming-convention": "off",
15+
"@typescript-eslint/prefer-nullish-coalescing": "off",
16+
"unicorn/no-array-reduce": "off"
17+
},
18+
"ignores": [
19+
"test/**",
20+
"examples/**"
21+
]
22+
}

README.md

+63-48
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,42 @@
1-
# [**koa-bodyparser**](https://github.com/koajs/bodyparser)
2-
1+
# [**@koa/bodyparser**](https://github.com/koajs/bodyparser)
32

43
[![NPM version][npm-image]][npm-url]
5-
[![build status][travis-image]][travis-url]
4+
![build status][github-action-image]
65
[![Coveralls][coveralls-image]][coveralls-url]
7-
[![David deps][david-image]][david-url]
86
[![node version][node-image]][node-url]
97

10-
[npm-image]: https://img.shields.io/npm/v/koa-bodyparser.svg?style=flat-square
11-
[npm-url]: https://npmjs.com/package/koa-bodyparser
12-
[travis-image]: https://img.shields.io/travis/koajs/bodyparser.svg?style=flat-square
13-
[travis-url]: https://travis-ci.org/koajs/bodyparser
8+
[npm-image]: https://img.shields.io/npm/v/@koa/bodyparser.svg?style=flat-square
9+
[npm-url]: https://www.npmjs.com/package/@koa/router
10+
[github-action-image]: https://github.com/koajs/bodyparser/actions/workflows/ci.yml/badge.svg?style=flat-square
1411
[coveralls-image]: https://img.shields.io/coveralls/koajs/bodyparser.svg?style=flat-square
1512
[coveralls-url]: https://coveralls.io/r/koajs/bodyparser?branch=master
16-
[david-image]: https://img.shields.io/david/koajs/bodyparser.svg?style=flat-square
17-
[david-url]: https://david-dm.org/koajs/bodyparser
18-
[node-image]: https://img.shields.io/badge/node.js-%3E=_8-green.svg?style=flat-square
13+
[node-image]: https://img.shields.io/badge/node.js-%3E=_14-green.svg?style=flat-square
1914
[node-url]: http://nodejs.org/download/
2015

21-
A body parser for koa, based on [co-body](https://github.com/tj/co-body). support `json`, `form` and `text` type body.
16+
Koa body parsing middleware, based on [co-body](https://github.com/tj/co-body). support `json`, `form` and `text` type body.
17+
18+
Parse incoming request bodies in a middleware before your handlers, available under the `ctx.request.body` property.
2219

23-
> Notice: this module doesn't support parsing multipart format data, please use [`@koa/multer`](https://github.com/koajs/multer) to parse multipart format data.
20+
> Notice: **This module doesn't support parsing multipart format data**, please use [`@koa/multer`](https://github.com/koajs/multer) to parse multipart format data.
2421
2522
## Install
2623

27-
[![NPM](https://nodei.co/npm/koa-bodyparser.png?downloads=true)](https://nodei.co/npm/koa-bodyparser/)
24+
[![NPM](https://nodei.co/npm/@koa/bodyparser.png?downloads=true)](https://nodei.co/npm/@koa/bodyparser)
25+
26+
```bash
27+
$ npm i @koa/bodyparser
28+
```
2829

2930
## Usage
3031

3132
```js
32-
const Koa = require('koa');
33-
const bodyParser = require('koa-bodyparser');
33+
const Koa = require("koa");
34+
const bodyParser = require("@koa/bodyparser");
3435

3536
const app = new Koa();
3637
app.use(bodyParser());
3738

38-
app.use(async ctx => {
39+
app.use((ctx) => {
3940
// the parsed body will store in ctx.request.body
4041
// if nothing was parsed, body will be an empty object {}
4142
ctx.body = ctx.request.body;
@@ -44,49 +45,61 @@ app.use(async ctx => {
4445

4546
## Options
4647

47-
* **enableTypes**: parser will only parse when request type hits enableTypes, support `json/form/text/xml`, default is `['json', 'form']`.
48-
* **encoding**: requested encoding. Default is `utf-8` by `co-body`.
49-
* **formLimit**: limit of the `urlencoded` body. If the body ends up being larger than this limit, a 413 error code is returned. Default is `56kb`.
50-
* **jsonLimit**: limit of the `json` body. Default is `1mb`.
51-
* **textLimit**: limit of the `text` body. Default is `1mb`.
52-
* **xmlLimit**: limit of the `xml` body. Default is `1mb`.
53-
* **strict**: when set to true, JSON parser will only accept arrays and objects. Default is `true`. See [strict mode](https://github.com/cojs/co-body#options) in `co-body`. In strict mode, `ctx.request.body` will always be an object(or array), this avoid lots of type judging. But text body will always return string type.
54-
* **detectJSON**: custom json request detect function. Default is `null`.
48+
- **patchNode**: patch request body to Node's `ctx.req`, default is `false`.
49+
- **enableTypes**: parser will only parse when request type hits enableTypes, support `json/form/text/xml`, default is `['json', 'form']`.
50+
- **encoding**: requested encoding. Default is `utf-8` by `co-body`.
51+
- **formLimit**: limit of the `urlencoded` body. If the body ends up being larger than this limit, a 413 error code is returned. Default is `56kb`.
52+
- **jsonLimit**: limit of the `json` body. Default is `1mb`.
53+
- **textLimit**: limit of the `text` body. Default is `1mb`.
54+
- **xmlLimit**: limit of the `xml` body. Default is `1mb`.
55+
- **jsonStrict**: when set to true, JSON parser will only accept arrays and objects. Default is `true`. See [strict mode](https://github.com/cojs/co-body#options) in `co-body`. In strict mode, `ctx.request.body` will always be an object(or array), this avoid lots of type judging. But text body will always return string type.
56+
- **detectJSON**: custom json request detect function. Default is `null`.
5557

5658
```js
57-
app.use(bodyParser({
58-
detectJSON: function (ctx) {
59-
return /\.json$/i.test(ctx.path);
60-
}
61-
}));
59+
app.use(
60+
bodyParser({
61+
detectJSON(ctx) {
62+
return /\.json$/i.test(ctx.path);
63+
},
64+
})
65+
);
6266
```
6367

64-
* **extendTypes**: support extend types:
68+
- **extendTypes**: support extend types:
6569

6670
```js
67-
app.use(bodyParser({
68-
extendTypes: {
69-
json: ['application/x-javascript'] // will parse application/x-javascript type body as a JSON string
70-
}
71-
}));
71+
app.use(
72+
bodyParser({
73+
extendTypes: {
74+
// will parse application/x-javascript type body as a JSON string
75+
json: ["application/x-javascript"],
76+
},
77+
})
78+
);
7279
```
7380

74-
* **onerror**: support custom error handle, if `koa-bodyparser` throw an error, you can customize the response like:
81+
- **onError**: support custom error handle, if `koa-bodyparser` throw an error, you can customize the response like:
7582

7683
```js
77-
app.use(bodyParser({
78-
onerror: function (err, ctx) {
79-
ctx.throw(422, 'body parse error');
80-
}
81-
}));
84+
app.use(
85+
bodyParser({
86+
onError(err, ctx) {
87+
ctx.throw(422, "body parse error");
88+
},
89+
})
90+
);
8291
```
8392

84-
* **disableBodyParser**: you can dynamic disable body parser by set `ctx.disableBodyParser = true`.
93+
- **enableRawChecking**: support the already parsed body on the raw request by override and prioritize the parsed value over the sended payload. (default is `false`)
94+
95+
- **parsedMethods**: declares the HTTP methods where bodies will be parsed, default `['POST', 'PUT', 'PATCH']`.
96+
97+
- **disableBodyParser**: you can dynamic disable body parser by set `ctx.disableBodyParser = true`.
8598

8699
```js
87-
app.use(async (ctx, next) => {
88-
if (ctx.path === '/disable') ctx.disableBodyParser = true;
89-
await next();
100+
app.use((ctx, next) => {
101+
if (ctx.path === "/disable") ctx.disableBodyParser = true;
102+
return next();
90103
});
91104
app.use(bodyParser());
92105
```
@@ -98,14 +111,16 @@ You can access raw request body by `ctx.request.rawBody` after `koa-bodyparser`
98111
1. `koa-bodyparser` parsed the request body.
99112
2. `ctx.request.rawBody` is not present before `koa-bodyparser`.
100113

101-
## Koa 1 Support
114+
## Koa v1.x.x Support
102115

103-
To use `koa-bodyparser` with koa@1, please use [bodyparser 2.x](https://github.com/koajs/bodyparser/tree/2.x).
116+
To use `koa-bodyparser` with koa@1.x.x, please use [bodyparser 2.x](https://github.com/koajs/bodyparser/tree/2.x).
104117

105118
```bash
106119
npm install koa-bodyparser@2 --save
107120
```
108121

109122
#### Licences
123+
110124
---
125+
111126
[MIT](LICENSE)
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
11
const Koa = require('koa');
2-
const bodyParser = require('.');
2+
const bodyParser = require('../../dist').default;
33

44
const app = new Koa();
55
app.use(bodyParser());
66

7-
app.use(async function() {
7+
app.use((ctx) => {
88
// the parsed body will store in this.request.body
9-
this.body = this.request.body;
9+
ctx.body = ctx.request.body;
1010
});
1111

1212
const PORT = process.env.PORT || 3000;
1313

1414
app.listen(PORT, () =>
15-
console.log(`Server ready at http://localhost:${PORT} 🚀 ..`)
15+
console.log(`Server ready at http://localhost:${PORT} 🚀 ..`),
1616
);

examples/esm/index.example.mjs

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import Koa from 'koa';
2+
import bodyParser from '../../dist/index.mjs';
3+
4+
const app = new Koa();
5+
app.use(bodyParser());
6+
7+
app.use((ctx) => {
8+
// the parsed body will store in this.request.body
9+
ctx.body = ctx.request.body;
10+
});
11+
12+
const PORT = process.env.PORT || 3000;
13+
14+
app.listen(PORT, () => console.log(`Server ready at http://localhost:${PORT} 🚀 ..`));

examples/typescript/index.example.ts

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import Koa from 'koa';
2+
import {bodyParser} from '../../src';
3+
4+
const app = new Koa();
5+
app.use(bodyParser());
6+
7+
app.use((ctx) => {
8+
// the parsed body will store in this.request.body
9+
ctx.body = ctx.request.body; // eslint-disable-line @typescript-eslint/no-unsafe-assignment
10+
});
11+
12+
const PORT = process.env.PORT || 3000;
13+
14+
app.listen(PORT, () => {
15+
console.log(`Server ready at http://localhost:${PORT} 🚀 ..`);
16+
});

0 commit comments

Comments
 (0)