Koa-respond - "ctx.badRequest" is not a function

System Information
  • Strapi Version: 4.20.1
  • Operating System: MacOs
  • Database: -
  • Node Version: -
  • NPM Version: -
  • Yarn Version: -

During an update/migration of a controller that works in version 4.14.5, to a Strapi project running version 4.20.1, I get the error that “ctx.badRequest” is not a function.

After doing I little research, I notice that this is a function that is part of the koa-respond package. I assume this pack is no longer part of the Strapi core. Hence I should rewrite it to something else.

There is no migration guide that describes this issue, going to the package.json of version 4.14.5 doesn’t mention koa (nor koa-respond) neither. So that might invalidate my thought process entirely. What strategy can you suggest to resolve issues as such?

module.exports = factories.createCoreController('api::lorem.lorem', ({
  strapi
}) => ({
  async create(ctx) {
    const requiredFields = ['name', 'role'];
    const {
      accent_color,
      name,
      role
    } = ctx.request.body.data;


    // Check if all required fields are present
    const missingFields = requiredFields.filter(field => !ctx.request.body.data[field])
    if (missingFields.length > 0) {
      return ctx.badRequest(null, [{
        messages: [{
          id: 'ValidationError',
          message: `Missing required fields: ${missingFields.join(', ')}`,
        }, ],
      }, ]);
    }
})

Noticing this file in the Strapi core of version 4.20.1: /packages/core/utils/src/parse-multipart.ts

This contains the following code

return ctx.badRequest(
      `When using multipart/form-data you need to provide your data in a JSON 'data' field.`
);

Can’t tell if this code would run eventually, cause yarn develop breaks on the previous error

⠋ Generating types/Users/jeffreyarts/repos/jeff-api/dist/src/api/lorem/controllers/ipsum.ts:20
        return ctx.badRequest(null, [
                   ^

TypeError: ctx.badRequest is not a function

According to the documentation, badRequest is the right way to go. So problem must be related to the way I have configured the controller.

I have not been able to reproduce exactly what I’ve been doing wrong. But I believe that this has been the problem.

** api/lorem/controllers.lorem.ts** (old)

module.exports = factories.createCoreController('api::lorem.lorem', ({
  strapi
}) => ({
  async create(ctx) {
        (...)
   }
})

** api/lorem/controllers.lorem.ts** (new)

const create =  async (ctx) {
        (...)
 }

export default {
    create
}

So in short, the error message was not really helpful. Running strapi generate was useful in this scenario, cause it gave me an outline of how a controller should be exported. No idea why it worked in my previous project, but than again. This kind of code inconsistency of mine is the sole reason I wanted to start a fresh and new project :wink: