m4nuC / async-busboy

Promise based multipart form parser for KoaJS
MIT License
167 stars 58 forks source link

using asyncBusboy in two middleware #36

Closed SergProduction closed 3 years ago

SergProduction commented 5 years ago

I have midllware for validate fields formData

const checkAndSendErrorValidateMiddleware = (schema, transformError) => async (ctx, next) => {
  const { fields, files } = await asyncBusboy(ctx.req)

  const filesFields = files.reduce((acc, fileReadStream) => ({ ...acc, [fileReadStream.fieldname]: fileReadStream }), {})

  const resultValidate = validate({ ...fields, ...filesFields }, schema)
  const errors = transformError(resultValidate.errors)
  if (resultValidate.errors.length !== 0) {
    ctx.body = JSON.stringify({
      errors,
      data: null,
    })
 }
 await next()
}

and controler midlleware

const controler = async (ctx, next) => {
  const { fields, files } = await asyncBusboy(ctx.req)

  const instanceModel = await db.findById(fields.id)
 // e.t.c
})

when I connect them in a chain, then in controler fields, files empty. Why?

route.post('/url', checkAndSendErrorValidateMiddleware(validateScheme), controler)
pepkin88 commented 3 years ago

It's probably because the ctx.req stream has already been consumed by the middleware, so there is nothing to read by the BusBoy in the controller. I suggest to store fields and files into the ctx.request object, in the middleware code.