Mathieu Bour
Mathieu Bour

Reputation: 696

Run NestJS scheduler without starting the HTTP server

I'm trying to create a "worker" for NestJS, which basically aggregate data from multiple datasources. Since I'm deploying this worker into into a Kubernetes Cluster, I don't need to start the NestJS inner HTTP server, however, the scheduler don't run without app.listen.

main.ts:

async function bootstrap() {
  const app = await NestFactory.create(WorkerModule);
  await app.listen(3030); // <-- I would like to delete this
}

bootstrap();

worker.module.ts

@Module({
  imports: [
    ScheduleModule.forRoot(),
  ],
  providers: [
    // Scrappers
    DataScrapper,
  ],
})
export class WorkerModule {}

data.scrapper.ts

@Injectable()
export class DataScrapper {
  @Interval(1000)
  async sync() {
    console.log('fetching...');
  }
}

Upvotes: 2

Views: 2313

Answers (1)

Jesse Carter
Jesse Carter

Reputation: 21147

At its core, NestJS is a modularized framework that provides strong DI capabilities to the node/TS ecosystem. A top level module can be exposed in one of three ways:

You can accomplish what you want by creating your application as a microservice with a custom strategy. I will most likely package this pattern up as part of the @golevelup/nestjs ecosystem (disclaimer, I am the author) as I have been encountering this pattern with increasing frequency lately.

import { CustomTransportStrategy } from '@nestjs/microservices';

class KeepAliveStrategy implements CustomTransportStrategy {
  private closing = false;

  wait() {
    if (!this.closing) {
      setTimeout(() => this.wait(), 1000);
    }
  }

  listen(callback: () => void) {
    callback();
    this.wait();
  }

  close() {
    this.closing = true;
  }
}

async function bootstrap() {
  const workerApp = await NestFactory.createMicroservice(WorkerModule, {
    strategy: new KeepAliveStrategy(),
  });

  await workerApp.listen(() => console.log('listening'));
}
bootstrap();

This will keep your worker alive and allow it to properly respond to NestJS lifecycle events

Upvotes: 5

Related Questions