typescriptnestjsguard

How to throw error using nest js guards without using any authentication module..?


Wanna send custom error in nestjs guards.

import { CanActivate, Injectable, ExecutionContext, NotFoundException } from '@nestjs/common';
import { Observable } from 'rxjs';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { UserParamsNotFoundException } from 'src/statusResponse/error.response';


@Injectable()
export class UserGuard implements CanActivate {
    constructor(
        @InjectModel(Users.name) private userModel: Model<CreateUser>,
    ) {}
    async canActivate(
        context: ExecutionContext,
    ): Promise<any> {
        const request = context.switchToHttp().getRequest();

        const { user, } = request.body; // u can extract the key using object destructing .
        const isUserExist: boolean = function (); // which will return true or false;
        
        return isUserExist ? true : false;


    }
};

enter image description here


Solution

  • Recently i am working on a project where there's no need of authentication. But, i have to check whether user exists in db or not before doing any CRUD operations. I used guard as decorator to tackle the problem. Pls find the below solution.

    import { CanActivate, Injectable, ExecutionContext, NotFoundException } from '@nestjs/common';
    import { Observable } from 'rxjs';
    import { InjectModel } from '@nestjs/mongoose';
    import { Model } from 'mongoose';
    import { UserParamsNotFoundException } from 'src/statusResponse/error.response';
    
    
    @Injectable()
    export class UserGuard implements CanActivate {
        constructor(
            @InjectModel(Users.name) private userModel: Model<CreateUser>,
        ) {}
        async canActivate(
            context: ExecutionContext,
        ): Promise<any> {
            const request = context.switchToHttp().getRequest();
    
            const { user, } = request.body; // u can extract the key using object destructing .
            const isUserExist: boolean = function (); // which will return true or false;
    
            if (!isUserExist) throw new NotFoundException('Oops User not exist. Try again');
            else return true;
        }
    };
    
    

    enter image description here

    Hope this is helpful..!!!