Comments (7)
Hello All.
SPOILER ALERT
First, to achieve that task one must understand how express router works (since nest uses express-like adapters under the hood).
the way it works is so simple, so i will try to introduce it in a simple examples and in our context only, since we are discussing how to nest routes, i will talk about it a little bit:
the notion of examples will be
HTTP_METHOD
/route
⇨ControllerClass@routerHandler
so in our ninja and cats example we have:
GET
/ninja
⇨NinjaController@sayHello
GET
/ninja/cats
⇨CatsController@sayHello
and what we need something like this:
GET
/ninja
⇨NinjaController@sayHello
GET
/ninja/all
⇨NinjaController@getAllNinja
GET
/ninja/:ninjaId
⇨NinjaController@getNinjaById
GET
/ninja/nested/cats
⇨CatsController@sayHello
GET
/ninja/:ninjaId/cats
⇨CatsController@sayHello
GET
/ninja/:ninjaId/cats/all
⇨CatsController@getAllCats
GET
/ninja/:ninjaId/cats/:catId
⇨CatsController@getCatById
...POST
/ninja/create
⇨NinjaController@createNinja
POST
/ninja/:ninjaId/cats/create
⇨CatsController@createCat
note the order of the above routes, you will know the reason next 😃
that's an easy task with nest & nest router
first, take this as a role of thump, Always put your static routes before the dynamic one, by static and dynamic here i mean, the route is static if it dose not have any params
in it, eg: /ninja/all
and it is said to be dynamic if it would have dynamic params
as in /ninja/:ninjaId
.
That's how express works in first place, the route matching will first try to match the requested route by the order they appears in the code, let's assume for a moment that express somehow uses a Map<string, (req, res, next) ⇨ T>
, and it calls Map#set
whenever it sees a new route, so for example:
// the map keys.
// []
router.get('/ninja', ...); // ['ninja']
router.get('/ninja/cats', ...); // ['ninja', 'ninja/cats']
... // and so on.
the reason i told that you need to put your static routes before the dynamic is how express do it,
for example: the user requested /ninja/5
as defined as /ninja/:ninjaId
then the ninjaId = 5
, right ?
what if we have also added a /ninja/cats
after that route ? Errors starts to happens, express will try to match the /ninja/:ninjaId
instead of /ninja/cats/
and bind the ninjaId
to cats
, boom !
try this here: https://runkit.com/shekohex/express-routes101
so back to our issue, it's now easy how we could achieve this
here is a way to do it
// routes.ts
import { Routes } from 'nest-router';
import { CatsModule } from './cats/cats.module';
import { DogsModule } from './dogs/dogs.module';
import { NinjaModule } from './ninja/ninja.module';
export const routes: Routes = [
{
path: '/ninja',
module: NinjaModule,
children: [
{ path: 'nested/cats', module: CatsModule }, // note how i added that before the next route ?!
{ path: ':ninjaId/cats', module: CatsModule }, // wanna play ? try to reverse order this route with 1st one
{ path: '/dogs', module: DogsModule },
],
},
];
now in your controllers, you can do what you want, but remember the role !
you can see/test/play with a full working example here: https://github.com/shekohex/nest-router/tree/master/examples/nest-v5x-m2m with all of the above routes implemented and tested.
from nest-router.
Brother @shekohex , thank you very much for your explanation.
This has served me well enough to be able to continue on.
You are undoubtedly the master of routes and module nesting.
Congratulations bro!
from nest-router.
That's a good question, I'm looking for exactly the same.
In order to manage the relationships in Nestjs.
Does anyone know how to manage the relationships in NestJs?
from nest-router.
I am looking for the same.
Missing that documentation on both sides.
How are handled many to many relationship in NestJs?
And how is it represented in routes?
from nest-router.
Hi @hzburki, good question.
I came with a simple answer to it, since expressjs already support the regex named routes why not just using it here 😃!
Try this:
Instead of @Get(':id')
do @Get('/:id(\\d+)/')
assuming that the id is always numbers.
That way it would first try to match the id, if it's number then it will call this method normally, if not (as in case of ninja/dogs
for example) it will fall through the next match which hopefully would be ninja/dogs
.
Sorry I can't test this way at this moment, I'm using my mobile phone 📱
from nest-router.
Please friend @shekohex , you are the nesting expert for routes and modules.
Please guide us on how to make relationships between classes and how to nest the routes and modules of relationships.
from nest-router.
Let's say you add a route to get a ninja by Id. I assume this route does not need to be defined inside the routes
file, rather we will just add another mothed with the @Get()
decorator.
@Get(':id')
getNinjaById(@Param('id') id: number){
// Some code here
}
The endpoint for this route would be;
API Endpoint: '/ninja/:id'
In this case, the path: '/dog'
sub-route (child route) for ninja defined in the answer above will not be accessible.
The ninja/:id
endpoint will always be evaluated before any of its children routes, therefore ninja/dog
will also be evaluated as ninja/:id
instead of ninja/dog
.
I am facing this error. How should I go about fixing this?
from nest-router.
Related Issues (20)
- There is no such a word like childrens in english HOT 1
- Params in nested routes and swagger HOT 3
- Difference to nestjs RouterModule ? HOT 1
- How to use versioning in v7? HOT 1
- dynamic path intercepts static HOT 4
- Require controller and http method instead of module HOT 1
- Intercepter per route (module) HOT 3
- An in-range update of @nestjs/core is breaking the build 🚨 HOT 3
- An in-range update of @nestjs/core is breaking the build 🚨 HOT 1
- Route resolving fails when setGlobalPrefix() is used HOT 5
- Nest-Router Adding Additional Slash before Controller HOT 4
- An in-range update of @nestjs/core is breaking the build 🚨 HOT 1
- Route gets double slash when try to define root level routes; `//users` instead of `/users` HOT 6
- Add a name to the routes HOT 3
- Defining routes as both nested and top level HOT 3
- Lack of documentation HOT 1
- Nested modules does not retain prefixes. HOT 2
- Child routes with parent modules HOT 2
- Question : What are the drawbacks of having route prefix at controller level instead of module level ? HOT 2
- [Problem] Order of evaluation of routes is the other way round HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from nest-router.