Search code examples
restmany-to-manydata-representation

Is it allowed to compute properties of an object for its representation?


I am facing the following situation:

I have a Post object, that is linked via a many-to-many relationship to a Commentobject. a Postcan have a maximum of 2 Comments marked as "Top".

I need to expose an API providing the function of listing Posts (aswell as showing a detailed view of a Post, but this one is okay). The problem is, that a Post can have a huge amount of Comments, and I don't see myself displaying this representation:

[{
   title: "Lorem ipsum",
   ....
   comments: [{
          "author": "...",
          "comment": ".....",
          "top": false
         }, ... // repeat a few thousand times
   ]
},...
]

However, I know that a majority of consumers of this API will later want to display directly the top comment(s), so I am thinking of exposing this representation:

[{
   title: "Lorem ipsum",
   ....
   topComments: [{
          "author": "...",
          "comment": ".....",
         }, .... // repeat once more if needed
   ]
},...
]

Here I choose not to display all the comments, which could be accessed through /posts/ID_OF_POST/comments, however I compute at "runtime" a topComments property (which is not in the original Object in the code), and display the comments marked as top

Is it allowed to compute using business logic and expose a property that doesn't exist in the object represented ? What if, later, I would like to add a new numberOfComments computed property, would it still be okay ?

Thank you in advance for your answers


Solution

  • Yes it's allowed, it's named "transient" or "virtual" properties.

    With Symfony Framework, you can do that like this.

    Hope this helps !!