0

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

3
  • Are you trying to do this ? : Mongoose Virtualtype. Maybe you don't use the right implementation, look at the bottom of the documentation.
    – Shim-Sao
    Oct 27, 2019 at 3:20
  • Nope, but i haven't any idea where to implement that in strapi :'(
    – ZecKa
    Oct 27, 2019 at 7:51
  • Why not using prototype like this cake.prototype.virtualproperty = 'what I want' ? I am new in strapi and I don't have tested that yet. What do you mean by virtual ? Just a custom property in return if I well understand ? It's very interesting. There is also the way to use maybe in the model afterFetch: async (model, response, options) => {} to add a property to the model.
    – Shim-Sao
    Oct 27, 2019 at 11:24

1 Answer 1

2

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;
}
1
  • I try but virtualproperty doesn't appear in api return :(
    – ZecKa
    Oct 28, 2019 at 15:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.