From the course: Mastering Nest.js: Build Scalable Applications with Mastery in Nest.js Framework

Unlock this course with a free trial

Join today to access over 25,200 courses taught by industry experts.

Limiting controller access with guard

Limiting controller access with guard

With the help of guards and its methods, we can also limit the controllers for accessing certain routes. Let's understand how we can achieve that. Inside the canActivate method, I'll create a constant named controller and assign the context.getClass method. As you can see the definition, it returns the type of controller class, which the current handler belongs to. So if I console log the controller and make a get request from the postman, then we get the class app controller in the terminal. So this get class method basically returns the controller to which the route handler belongs to. And using this method, we can restrict the controllers for accessing the routes. So let's assume a scenario that this app controller is the admin, and I will create one more controller. Let's name it as user controller. And I will also create a service file under the services folder, naming it as user service. So here is the user controller and the service file. I'll first open the service file. And…

Contents