How access request params in middleware in nest.js

I Have a middleware in my nest.js app and this middleware checks all the routes that have userId param, and if the userId doesn’t exists in database, throw not found expection:

import {
    Inject,
    Injectable,
    NestMiddleware,
    NotFoundException,
} from "@nestjs/common";
import {Profile} from "../../database/models";
import {PROFILE_REPOSITORY} from "../constant";
import {Response, Request} from "express";
import {decodeJwt} from "../libs";

@Injectable()
export class UserExistMiddleware implements NestMiddleware {
    constructor(
        @Inject(PROFILE_REPOSITORY)
        private readonly profileRepository : typeof Profile,
    ) {}
    async use(req: Request, res: Response, next: NextFunction,) {

        const {userId} = req.params;

        if (!userId)  next();

        const user = await this.profileRepository.findOne({
            where: {
                id: userId
            }
         })

        if (!user) throw new NotFoundException();
        
        next();
    }
}

This is one of my endpoints that have userId param : /api/v1/parent/getChild/:userId

And when I call it, I can’t access to route param in this middleware and when I console req.params returns this :

{ '0': 'parent/getUser/248' }

I console and watch req params but I didn’t any thing that related to ‘userId’

Also this is my app.module file that I import my middleware:

export class AppModule implements NestModule {
    configure(consumer: MiddlewareConsumer): any {
        consumer.apply(ChildExistMiddleware).forRoutes({
            path: '*',
            version: '1',
            method: RequestMethod.ALL
        });
    }
}

I tasted this value for path, but didn’t work : path: '*/:userId'

So how can I access to all endpoints that have ‘userId’ param?

Leave a Comment