#Get all registered routes in a module function
14 messages · Page 1 of 1 (latest)
You could inject the HttpAdapterHost and get the HttpAdapter from there, and then get the routes
ty.
I saw a solution that worked but I don't know if it's a best practice.
Create a app.instance.ts file with a variable instance and a function to get the instance:
import { INestApplication } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
let instance;
export async function getAppIntance(): Promise<INestApplication> {
if (!instance) {
instance = await NestFactory.create(AppModule, { bufferLogs: true });
}
return instance;
}
and in bootstrap call that method...
Whenever I need to get the app I just need to call the method anywhere.. But this doesn't seem to be a good practice...
Why would you need the NestApplication instance outside of main? What would that achieve over injecting the HttpAdapterHost?
That's why I thought it was not a good practice 🙂
ty
Is there anyway to "mock" the httpAdapterHost or it's best to mock the method where it's called? Not a full code coverage with that, though..
Just like you would any other provider
hi,
when I get the routes in the adapter using:
const httpAdapter = this.adapterHost.httpAdapter;
if (!this.adapterHost.httpAdapter) return [];
const server = httpAdapter.getHttpServer();
const router = server._events.request._router;
const availableRoutes: [] = router.stack
// eslint-disable-next-line array-callback-return
.map((layer) => {
if (layer.route) {
console.log(JSON.stringify(layer));
const alias = `${(
layer.route.stack[0].method as string
).toLowerCase()}_${layer.route.path as string}`;
return {
alias,
verb: layer.route.stack[0].method,
path: layer.route.path,
type: 'private',
};
}
})
.filter((item) => item?.path.startsWith('/api'));
is there a way of knowing on which controller the route was used, except for parsing the path?
thanks
Layer outputs:
{
"name": "bound dispatch",
"keys": [],
"regexp": { "fast_star": false, "fast_slash": false },
"route": {
"path": "/docs/swagger-ui-init.js",
"stack": [
{
"name": "<anonymous>",
"keys": [],
"regexp": { "fast_star": false, "fast_slash": false },
"method": "get"
}
],
"methods": { "get": true }
}
}
Express will have 0 information on the controller classes you used
damn.. If I use RouterModule to register the module will I be able to get more information?