Search code examples
reactjsapinext.jscontent-management-systemstrapi

Modify every data response in strapi


Im wondering what the best way to execute a function before the any data is returned from the api so that i can modify the data response.

I know that i could add the function to every single controller however this would mean repeating myself a lot of times. Policies seemed like the correct thing to do however these will execute before the controller is hit.

Anyone know how to do this?

module.exports = {
  async find(ctx) {
    let entities;
    ctx.resp... // altering the data this way at the moment

Solution

  • A policy can be made to execute after the controller function has been executed the code has to come after the await next() as shown below.

    module.exports = async (ctx, next) => {
      // Indicate to the server to go to
      // the next policy or to the controller's action.
      await next();
    
      // The code below will be executed after the controller's action.
      if (ctx.status === 404) {
        ctx.body = 'We cannot find the resource.';
      }
    };
    

    kindly refer :Advanced usage