Execution Context
There are several ways of mounting the Nest application. You can create a web app, microservice or just a Nest execution context. The Nest context is a wrapper around the Nest container, which holds all instantiated classes. We can grab any existing instance from within any imported module directly using application object. Thanks to that, you can take advantages of the Nest framework everywhere, including CRON jobs and even build a CLI on top of it.
To create a Nest application context, we are using the following syntax:
async function bootstrap() {
const app = await NestFactory.createApplicationContext(ApplicationModule);
// logic.. :)
}
bootstrap();
Afterwards, Nest allows you to pick any instance registered within Nest application.
Let's imagine that we have a TasksController in the TasksModule.
This class provides a set of usable methods, which we want to call from within CRON job.
const app = await NestFactory.create(ApplicationModule);
const tasksController = app
.select(TasksModule)
.get(TasksController);
And that's it. To grab TasksController instance we have used 2 methods, well-described in the below table:
get()
|
Makes possible to retrieve the instance of the component or controller available inside the processed module. |
select()
|
Allows you to navigate through the module tree, for example, to pull out a specific instance from the selected module. |
Hint The root module is selected by default. To select any other module, you need to go through entire modules stack (step by step).