Closed sergeysova closed 5 years ago
It changes allows passing the result of middleware from one to each other. I use this concept to realize the functional pattern in middlewares.
You already returns result of next()
:
https://github.com/koajs/bodyparser/blob/master/index.js#L73-L74
Without that fix, I can't propagate data from middleware to middleware without changing context
@dead-horse
the koa middleware don't has a 'result' concept.
Any news regarding this?
This would allow koa-bodyparser
to be used with patterns which depend on the return value without having to mount the bodyparser for the entire application.
For example, I'm using a pattern where I simply return objects from my handlers, then serialize them as I wish when the stack unwinds:
const Koa = require('koa')
const mount = require('koa-mount')
const Router = require('koa-router')
const app = new Koa()
const jsonResponse = async (ctx, next) => {
const body = JSON.stringify(await next()) // <---- "await next()" currently returns undefined
ctx.status = ctx.status || 200
ctx.body = body
ctx.type = 'json'
}
const fooApi = new Router()
fooApi.use(bodyParser())
fooApi.get('/foo', async () => {
return await service.getFoos()
})
app
.use(jsonResponse)
.use(mount('/api', fooApi))
As the bodyparser is mounted at the API router level and not at the app level, my JSON serialization middleware breaks because the return value is not passed through with return
. I would much prefer not to enable the bodyparser at the app level, as the functionality is really not needed for the other routers in my app.
Any updates?
Any news regarding this?
This would allow
koa-bodyparser
to be used with patterns which depend on the return value without having to mount the bodyparser for the entire application.For example, I'm using a pattern where I simply return objects from my handlers, then serialize them as I wish when the stack unwinds:
const Koa = require('koa') const mount = require('koa-mount') const Router = require('koa-router') const app = new Koa() const jsonResponse = async (ctx, next) => { const body = JSON.stringify(await next()) // <---- "await next()" currently returns undefined ctx.status = ctx.status || 200 ctx.body = body ctx.type = 'json' } const fooApi = new Router() fooApi.use(bodyParser()) fooApi.get('/foo', async () => { return await service.getFoos() }) app .use(jsonResponse) .use(mount('/api', fooApi))
As the bodyparser is mounted at the API router level and not at the app level, my JSON serialization middleware breaks because the return value is not passed through with
return
. I would much prefer not to enable the bodyparser at the app level, as the functionality is really not needed for the other routers in my app.
Why not use ctx.request.body
directly after koa-bodyparser
handled in function jsonResponse
, like below:
const body = JSON.stringify(ctx.request.body)
Out of curiosity, what is the purpose of this change?