Skip to content

Commit

Permalink
Patch empty body breaking includeUnparsed
Browse files Browse the repository at this point in the history
  • Loading branch information
zevisert committed Jan 12, 2019
1 parent 2f9054b commit 7ed6b36
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
6 changes: 3 additions & 3 deletions index.js
Expand Up @@ -101,9 +101,9 @@ function requestbody(opts) {
ctx.req.body = body.fields;
ctx.req.files = body.files;
} else if (opts.includeUnparsed) {
ctx.req.body = body.parsed;
ctx.req.body = body.parsed || {};
if (! ctx.is('text')) {
ctx.request.body[symbolUnparsed] = body.raw;
ctx.req.body[symbolUnparsed] = body.raw;
}
} else {
ctx.req.body = body;
Expand All @@ -114,7 +114,7 @@ function requestbody(opts) {
ctx.request.body = body.fields;
ctx.request.files = body.files;
} else if (opts.includeUnparsed) {
ctx.request.body = body.parsed;
ctx.request.body = body.parsed || {};
if (! ctx.is('text')) {
ctx.request.body[symbolUnparsed] = body.raw;
}
Expand Down
28 changes: 27 additions & 1 deletion test/index.js
Expand Up @@ -275,7 +275,7 @@ describe('koa-body', () => {
let requestSpy;

beforeEach(() => {
app.use(koaBody({ includeUnparsed: true}));
app.use(koaBody({ includeUnparsed: true }));
app.use(router.routes());
});

Expand All @@ -284,6 +284,32 @@ describe('koa-body', () => {
requestSpy = undefined;
});

it('should not fail when no request body is provided', (done) => {
const echoRouterLayer = router.stack.filter(layer => layer.path === "/echo_body");
requestSpy = sinon.spy(echoRouterLayer[0].stack, '0');

request(http.createServer(app.callback()))
.post('/echo_body')
.type('application/json')
.send(undefined)
.expect(200)
.end((err, res) => {
if (err) return done(err);

assert(requestSpy.calledOnce, 'Spy for /echo_body not called');
const req = requestSpy.firstCall.args[0].request;

req.body.should.be.null;
res.body.should.have.properties({});

req.body[unparsed].should.not.be.undefined;
req.body[unparsed].should.be.a.String;
req.body[unparsed].should.have.length(0);

done();
});
});

it('should recieve `urlencoded` request bodies with the `includeUnparsed` option', (done) => {

const userRouterLayer = router.stack.filter(layer => layer.path === "/users" && layer.methods.includes('POST'));
Expand Down

0 comments on commit 7ed6b36

Please sign in to comment.