Skip to content

iamolegga/nestjs-configure-after

Repository files navigation

nestjs-configure-after

npm npm GitHub branch checks state Known Vulnerabilities Libraries.io Dependabot

Using NestJS?

Do you have middlewares set via configure(consuer: MiddlewareConsumer) {} and want to control the order of execution of these middlewares?

Install

npm i nestjs-configure-after

Example

Let's assume we have ModuleA, ModuleB, and ModuleC, and each has its own middleware setup. And we want these middlewares to be set in the correct order, like A -> B -> C. By default NestJS does not provide the way to set the order. But with this library it's possible:

import { After } from 'nestjs-configure-after'

@Module({})
//
// Empty if independent
//
@After()
class ModuleA {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(FirstMiddleware)
      .forRoutes('*');
  }
}

@Module({})
//
// Pass module that should configure it's middlewares
// before the current one
//
@After(ModuleA)
class ModuleB {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(SecondMiddlewareThatShouldBeExecutedAfterTheFirstOne)
      .forRoutes('*');
  }
}

@Module({})
//
// ...Or even pass several modules
//
@After(ModuleA, ModuleB)
class ModuleC {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(TheLastMiddleware)
      .forRoutes('*');
  }
}

@Module({
  // And for now it does not matter in which
  // order modules are set in `imports` field
  // Middlewares will be setup in the right order.
  imports: [ModuleC, ModuleA, ModuleB, ...],
  controllers: [...]
})
class App {}

Do you use this library?
Don't be shy to give it a star! ★

Also if you are into NestJS you might be interested in one of my other NestJS libs.