typescript 如何在不使用任何认证模块的情况下使用nest js guards抛出错误?

ubbxdtey  于 2023-01-06  发布在  TypeScript
关注(0)|答案(1)|浏览(124)

要在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;

    }
};

hgqdbh6s

hgqdbh6s1#

最近我在做一个不需要认证的项目,但是在做CRUD操作之前,我必须检查用户是否存在于数据库中。我用guard作为装饰器来解决这个问题。请找到下面的解决方案。

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;
    }
};

希望这对你有帮助。

相关问题