Search code examples
koakoa2

How to distinguish koa ctx is multipart/form-data type or not?


So i'm using koa2, if this request is multipart type, believe i need to process

    ctx.request.body.fields

otherwise i process

    ctx.request.body

So what's the best way to distinguish and handle these 2 cases ?


Solution

  • I guess my point of view is, if you're needing to check for a form submission as well as other activity, then perhaps your endpoint is doing a bit much? It very much depends on your use case of course, but keeping form data and other content types separate may be a clearer API.

    Having said that, I don't see any reason to get more complicated than checking for the presence of fields. koa-body is a great way to go about this.

    One thing you might like to consider is using the middleware stack to your advantage. For example, only do stuff if there's a form submission but allow other actions to take place:

    router.post('/', koaBody({ multipart: true }),
      async (ctx, next) => {
        if (ctx.request.body.fields) {
          // Handle form if present
        }
        await next() // Pass control down the stack
      }
    ))