Ankur Verma
Ankur Verma

Reputation: 5933

Getting the metadata of the Module in NestJs

So, I came across a situation where I need to get the metadata of the Current Module, and its controllers.

ClosedModule.ts

// all imports to AModule, BModule
@Module({
    imports: [
        DiscoveryModule, // given by nest/core
        AModule, // it has a controller AController whose base path is A/ and has 1 function for @Get a1
        BModule, // it has a controller BController whose base path is B/ and has 1 function for @Get b1
    ],
})
export class ClosedModule implements OnModuleInit { // ---> (X)

    constructor(private readonly discovery: DiscoveryService) {}

    public async onModuleInit() {
        const controllers = await this.discovery.getControllers({});
        controllers.map(c => console.log('---->', c.name));
    }
}

In above code:

DiscoveryService, DiscoveryModule imported from '@nestjs/core';

I tried getting the information using the above code. But, there are some issues:

  1. I am getting all the controllers in the array, rather I just need the controllers refs for the ClosedModule class i.e current class, (X).

  2. How can I get the base path of all the controllers under a module which IMPORTED.

    2.1 Other modules

    2.2 Other Controllers

Thanks in advance Happy Coding :)

Upvotes: 2

Views: 5155

Answers (2)

OSA413
OSA413

Reputation: 486

The only thing that I found working is making a function that returns module metadata, then I can use the metadata as I wish (including making changes before module creation).

Main module file:

export const getModuleMetadata = (): ModuleMetadata => {
    return {} //the metadata
}

@Module(getMetadata())
export class MyModule {}

Test file:

import {getModuleMetadata} from "main_file"

const nestModule = await Test.createTestingModule(getModuleMetadata()).compile();
const app = module.createNestApplication();
await app.init();

Upvotes: 0

csakbalint
csakbalint

Reputation: 796

You have access to a container in your module's constructor, which has all the configurations given to the imported modules.

Here

@Module({})
export class YourModules {
  constructor(readonly modulesContainer: ModulesContainer) {
    const modules = [...modulesContainer.values()];
    for (const nestModule of modules) {
      const modulePath: string = Reflect.getMetadata(MODULE_PATH, nestModule.metatype);
    }
  }
// ...
}

You can find a more detailed example in the nestjsx/nest-router library.

Upvotes: 0

Related Questions