Search code examples
strapi

Add virtual properties in Strapi


Is there a way to add virtual property in api response object ?

I tried to do this in the controller, but the values I add are not displayed in the API return.

My goal is to dynamically define the value of the virtual field according to the current day.

findOne: async ctx => {
    if (!ctx.params._id.match(/^[0-9a-fA-F]{24}$/)) {
      return ctx.notFound();
    }
    const cake = strapi.services.cake.fetch(ctx.params);
    cake.virtualproperty = "test to add value in api return";
    return cake;
}

ps: I try to do this in strapi cake example project


Solution

  • You missed to await your function. Should be this following code:

    findOne: async ctx => {
        if (!ctx.params._id.match(/^[0-9a-fA-F]{24}$/)) {
          return ctx.notFound();
        }
        const cake = await strapi.services.cake.fetch(ctx.params);
        cake.virtualproperty = "test to add value in api return";
        return cake;
    }