What's the best way to do stuff when Nestjs application loads?

Viewed 4172

When my Nest.js application loads, i need to run some database operations. (mainly around data initialization). All these tasks are already built and working as actions in controllers. If i go manually to /api/controller/action - they work. I need a way to call each one of them when the server loads up. Any advice?

1 Answers

NestJS exposes a few lifecycle hooks that you can implement in a service (or somewhere else for that matter). You simply create a service implementing the lifecycle hook you need and register it as a provider with your AppModule.

For instance:

@Injectable()
export class WarmupService implements OnApplicationBootstrap {
    constructor(
        private readonly db: Db
    )

    onApplicationBootstrap() {
        this.db.doDataInitialization();
    }
}

You don't necessarily have to create a new service for this, you could also simply place this hook directly in your AppModule (or any other module for that matter).

You can read more in the documentation.

Before NestJS

If you instead need to run some logic before NestJS is initialized (and none of the lifecycle hooks above match), you can simply run it in the main.ts file before the call to app.listen(..).

Related