Search code examples
viewmodelsm2m

Web api: Retrieve m2m model vs Retrieve main model


I have a code-design question. Lets say we have a web app with a web service (rest api) and the models User, Job and also JobFavorite. JobFavorite model is a m2m model with fields user and job, meaning that a user can mark a job as favorite.

Lets say that we have two views.

  1. The job list view, where the user sees all available jobs for him.

  2. A filtered job list view, where the user sees only the jobs that has marked as favorite.

In both views, the user can perform same actions: Apply for a job and (un)mark job as favorite.

In the first view, we make an ajax call to our api to retrieve all available jobs. The question has to do with the second view.

Should we call the job api and retrieve job models or should we call the JobFavorite api and retrieve JobFavorite models and then user the JobFavorite.job field inside the template?

I hope the question is clear and follows asking rules.

Update: Classes in pseudocode:

class Job():
    owner - foreign key(User)
    ...etc

class JobFavorite():
    user - foreign key(User)
    job  - foreign key(Job)

class User():
    name
    phone

Solution

  • I wouldn't complicate the matters on a frontend with a new model / api / controller (JobFavourite) in this particular case unless it is absolutely necessary. I would make "favourite" a filter on Job's controller.

    So, on a filtered job list view you call GET /jobs?favourites=true to get only favourited user jobs. On the backend however, this can be implemented using different strategies. You can use separate JobFavourite model to store favourites. Or make json / array field on User model to store his favourites (use the latter two with caution).

    This suggestion has also another positive. Treating is_favourite "flag" as a filter you allow to work with jobs uniformly (applying another filter is easy here).