Strapi transformresponse

System Information
  • Strapi Version: 4.4.5
  • Operating System: Win

Strapi transformResponse usage

All this time when I needed to write my controller. I transformed the answer like this:

   // Fetching data
   const { results, pagination } = await strapi
      .service("api::category.category")
      .find(query);
   
   // Sanitize
   const sanitizedEntity = await this.sanitizeOutput(results, ctx);
  
   // Transform data
   const transformed = this.transformResponse(sanitizedEntity);

   // Return with meta assigned
   return { data: transformed.data, meta: pagination };

But it turns out you can do it this way:

   // Fetching data
   const { results, pagination } = await strapi
      .service("api::category.category")
      .find(query);
   
   // Sanitize
   const sanitizedEntity = await this.sanitizeOutput(results, ctx);

   // Transform can accept second argument as meta
   return this.transformResponse(sanitizedEntity, pagination)

I found no information about this in the documentation can be useful to anyone :slightly_smiling_face:

2 Likes

Awesome thanks for this.
Where can we find more information on how to use this correctly and the parameters etc.

Try looking in the documentation. It may have already been updated since last time.
Also keep in mind that this.transformResponse handles the response specifically to this controller’s data schema =)

For example I had an endpoint where I had to combine and process data before output, and I couldn’t understand why some fields are processed by transformation and some are not, it was just because of the processing by data type.