Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Other body types #965

Closed
franciscop opened this issue Apr 19, 2017 · 1 comment
Closed

Other body types #965

franciscop opened this issue Apr 19, 2017 · 1 comment

Comments

@franciscop
Copy link
Contributor

franciscop commented Apr 19, 2017

While in the documentation it states that the body will return a JSON object if the body is set to an object, I found out that arrays also work the same way:

ctx.body = ['foo', 'bar'];

This is awesome, but it might be a bug since in the code for that part the leftovers are treated as JSON:

set body(val) {
    // ...
    if ('string' == typeof val) // ...
    if (Buffer.isBuffer(val)) // ...
    if ('function' == typeof val.pipe) // ...
    
    // Everything else
    this.remove('Content-Length');
    this.type = 'json';
}

Notably this makes other things work:

app.use(ctx => {
  ctx.body = false;
});

But some other things won't:

app.use(ctx => {
  ctx.body = () => {
    console.log('Hello there!');
  };
});

Is this an intended feature? Everything that is not one of the above is just treated as JSON?

Notably in counter-intuitive examples, this will work and return a json {} with a status code 200 (I know about throw(), just pointing out this works not as expected and might be confusing):

app.use(ctx => {
  ctx.body = new Error('I work!');
});
@jonathanong
Copy link
Member

jonathanong commented Apr 30, 2017

we didn't bother guarding against everything a dev could put as a response body. returning a function simply doesn't make sense. returning a boolean could make sense. an error works, but it doesn't work as intended as some properties of an error are not enumerable.

personally, i would just add middleware in the app that asserts body types per app. the framework should remain minimal.

app.use(async (ctx, next) => {
  await next()

  ctx.assert.equal('object', typeof ctx, 500, 'some dev did something wrong')
})

this is only a few lines of code and could be tailored to each app

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants