What is the method for throwing errors with NestJS guards without relying on an authentication module?

Are you looking to customize error responses 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; // Extract keys using object destructuring.
        const isUserExist: boolean = function (); // Function returning true or false based on conditions.
        
        return isUserExist ? true : false;


    }
};

https://i.sstatic.net/vdyMH.png

Answer №1

Currently, I am immersed in a project that does not require authentication. However, it is essential to verify whether the user exists in the database before performing any CRUD operations. To address this issue, I implemented the use of a guard as a decorator. You can find the solution provided below.

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; // you can extract the key using object destructuring.
        const isUserExist: boolean = function (); // a function that will return true or false;

        if (!isUserExist) throw new NotFoundException('Oops! User does not exist. Please try again.');
        else return true;
    }
};

https://i.sstatic.net/TYpbZ.png

I trust this information proves to be beneficial!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular Deprecates Event before Unload Event

My goal is to prevent the user from navigating to any link if there are unsaved changes, and it works correctly in most cases but there are two exceptions: When the user clicks on "Log Out" When the user clicks on a toggle button at the layout level I at ...

Utilize information gathered through subscription to populate the List

Objective: Achieve the retrieval of output data { age: 4, name: 'Foo' } { age: 7, name: 'Bar' } and subsequently utilize this output data in the variable list labeled as "PersonList: Person[] = [];" Challenge: I have attempted v ...

Downloading PDF files on IOS while using Angular often results in the PDF opening in the same

I'm currently utilizing file-saver within my Angular application to retrieve a PDF generated from the backend. The library functions smoothly on desktop and Android devices, but I'm encountering issues with downloading files on iOS. Contrary to w ...

When processing JSON data, Typescript is unable to interpret a map<string,string> structure

I am currently working with Angular5 within a spring boot application and I am attempting to retrieve a Map object in JSON format. Spring : //sample method return ResponseEntity.ok((new Gson()).toJson(/*My map object*/)); Angular5 : sql_list = new Map& ...

What are the steps for integrating and expanding a JavaScript library using rollup, TypeScript, and Angular 2?

I am currently working on a project called angular2-google-maps-test and I am interested in integrating and expanding upon the JS library found at js-marker-clusterer npm install --save js-marker-clusterer It seems that this library is not structured as ...

Unable to bring in CSS module in a .tsx file

I am currently working on a basic React application with TypeScript, but I am encountering difficulty when trying to import a CSS file into my index.tsx file. I have successfully imported the index.css file using this method: import './index.css&apo ...

Leveraging TypeScript's declaration file

Greetings! I am currently facing an issue while utilizing a declaration file in my TypeScript project. Here is the declaration file that I am working with: // Type definitions for Dropzone 4.3.0 // Project: http://www.dropzonejs.com/ // Definitions ...

Having difficulty initializing a new BehaviourSubject

I'm struggling to instantiate a BehaviourSubject I have a json that needs to be mapped to this Typescript class: export class GetDataAPI { 'some-data':string; constructor (public title:string, public description:string, ...

Tips for obtaining a subset of `keyof T` where the value, T[K], refers to callable functions in Typescript

Is there a way to filter keyof T based on the type of T[keyof T]? This is how it should function: type KeyOfType<T, U> = ... KeyOfType<{a: 1, b: '', c: 0, d: () => 1}, number> === 'a' | 'c' KeyOfType<{a: ...

Number as the Key in Typescript Record<number, string> is allowed

As a newcomer to TypeScript, I am still learning a lot and came across this code snippet that involves the Record utility types, which is quite perplexing for me. The code functions correctly in the playground environment. const data = async (name: string ...

Tips for including a dash or hyphen in an input field after two digits in Angular 4

Struggling to format the date of birth input with dashes manually when entered by the user. The desired output should resemble "08-18-2019," but I'm having difficulty achieving this. public dateOfBirth: { year: number; month: number; day: number }; ...

Overriding a generic property in Typescript allows for a more

I'm troubleshooting an issue with my code: class Base<T> {} class Test { prop: Base<any>; createProp<T>() { this.prop = new Base<T>(); } } const test = new Test(); test.createProp<{ a: number }>(); test.pr ...

The operation state.concat cannot be performed as it is meant for arrays and not for type 'ITask'

Trying to incorporate an array into my store is causing issues with the following error popping up at tasks: payload.payload ? [ ...state, payload.payload ] : []: Error:(22, 35) TS2461: Type 'ITask' is not an array type. Any suggestions on how t ...

What are some solutions to the "t provider not found" error?

Upon deploying my application on the production server using GitLab/Docker, I encountered the following error message: ERROR Error: No provider for t! at C (vendor.32b03a44e7dc21762830.bundle.js:1) at k (vendor.32b03a44e7dc21762830.bundle.js:1) at t._thr ...

Tips for utilizing the React Redux useDispatch hook within a RTL test

After incorporating a redux dispatch, I am seeking to conduct testing on a React component. To achieve this, I have adopted a personalized render function from the "test-utils.ts" document: import { ReactElement } from 'react' import { render, Re ...

While utilizing the imodel.js front-end for designing a custom geometric model, I ran into an issue while trying to display it

Utilizing imodel.js front-end, I was able to design a customized geometric model featuring elements like a collection box. However, when placing the model within the existing SpatialViewState in bim, it failed to display properly in the current view. Sub ...

TypeScript causing issues when multiple selectors are used

Currently, I have a function that allows me to search for HTML elements based on text content: function findElementsByText(text: string): HTMLElement[] { const selectors = 'button' // This conditional statement ensures that an empty text quer ...

Improving the App() function in React and Typescipt

When working on my React/Typescript app, I encountered a challenge with the length of the code in one of the sections. Despite watching tutorials and searching for solutions, I couldn't find a clear way to refactor it. The specific issue is with refa ...

Using Ionic's ngmodel directive with a list and associating ids as keys

Having an issue. Trying to connect a toggle button with a list and use the toggle's id as a key. //Function for conversion transform(d) { alert(d); //when i put this.id here i have undefined value return Number(d); } <ion ...

Tips for utilizing mergeWith with Subjects in an Angular application

Objective: Creating a Combined Filter with 3 Inputs to refine a list Conditions: Users are not required to complete all filters before submission The first submit occurs when the user inputs data Inputs are combined after more than one is provided Appro ...