Search code examples
javascriptrestarchitecturenestjs

Nestjs, Where to handle relation between ressources in a restApi


In a nestjs restful api using mongoose, what is the common (and good) way to handle the relation between ressources. My project follow almost this structure, the only difference is i use repository instead of entity.

Taking the example with a Cat repository (from the nestjs documentation), i can have another Food repository. This is not exclusif to the cat, it contains all kinds of food, but contains some Cat food too.

If i want to get the food related to my type of Cat, taking the restful api requirement, my endpoint will be:

/cat/:type/foods

This seems pretty clear and i like it.

Now, in my real app i have the following structure: enter image description here

Like you can see, each ressources have a link with the oher at one moment. So, what the path need to be for each ressources when i for exemple get one by ID or when i get it with the relation?


Resources use:

https://www.infoq.com/articles/rest-introduction/ relation for orders

https://docs.nestjs.com/controllers#routing


Solution

  • In my opinon, because it's a many-to-many relationship. you should follow the offical JSONAPI documentation: https://jsonapi.org/recommendations/#urls-relationships

    In case you want to find a Cat's food (1 to many), you should use the following url schema:

    /cats/:type/relationship/food
    

    In case you want to find the cats that relate to a specific food (1 to many), you should use the following url schema:

    /food/:type/relationship/cats