Jason Brook
Jason Brook

Reputation: 35

How to pass parameters to the use function inside the middleware when consuming the middleware in Nest js

How can i pass parameters from here

export class NotificationModule implements NestModule{
  public configure(consumer: MiddlewareConsumer) {
    consumer.apply(AuthMiddleware).forRoutes(
        {path: 'notification/create', method: RequestMethod.POST},

And How can I use passed parameters in here

@Injectable()
export class AuthMiddleware implements NestMiddleware {
    constructor(private readonly studentService: StudentService) {
    }

    async use(req: Request, res: Response, next: NextFunction) {
       ????????
    }

Upvotes: 1

Views: 4137

Answers (2)

Aleksey Malashenok
Aleksey Malashenok

Reputation: 69

I think you can use mixin pattern here, so solution migth look like

module

export class NotificationModule implements NestModule{
  public configure(consumer: MiddlewareConsumer) {
    consumer.apply(AuthMiddlewareCreator({ value: true })).forRoutes(
        {path: 'notification/create', method: RequestMethod.POST},

and mixin

import { Injectable, mixin, NestMiddleware, Type } from '@nestjs/common';
...
export function AuthMiddlewareCreator(options: AuthMiddlewareOptions): Type<NestMiddleware> {

    @Injectable()
    class AuthMiddleware implements NestMiddleware {
      constructor(private readonly studentService: StudentService) {
      }

      async use(req: Request, res: Response, next: NextFunction) {
        // you can use options here, for example
        const { value } = options;
       ...
     }
  }
  return mixin(AuthMiddleware);
}

Upvotes: 1

Micael Levi
Micael Levi

Reputation: 6665

since middlewares are injectables, you could pass the options as any other provider like this one in which the options are passed in the module here

or use create-nestjs-middleware-module to turn middlewares into modules

or make a mixin that will return the middleware. Thus, you will pass the options like consumer.apply(CreateAuthMiddleware(opts))

Upvotes: 0

Related Questions