Guide to accessing the request object within the entity class in NestJS

Currently tackling a project in nestJs that requires adding audit columns to certain entities. I have set up user information on a request object, which seems to be working fine when printed in the controller. However, I am facing issues with implementing this in entity classes.

My attempted approach is as follows:

import { Req } from "@nestjs/common";
import { Exclude } from "class-transformer";
import { BeforeInsert, BeforeUpdate, Column, CreateDateColumn, DeleteDateColumn, PrimaryGeneratedColumn, UpdateDateColumn } from "typeorm";

export class BaseModel{
    @PrimaryGeneratedColumn('uuid')
    id:string

    @CreateDateColumn()
    created_at:Date

    @Column({default:null})
    created_by:string

    @UpdateDateColumn()
    modified_at:Date

    @Column({default:null})
    modified_by:string

    @DeleteDateColumn({select:false})
    @Exclude()
    deleted_at:Date

    @BeforeInsert()
    setAuditsBeforeInsert(@Req() req:any){
        this.created_by=req.currentUser.id;
        this.modified_by=req.currentUser.id;
    }

    @BeforeUpdate()
    setAuditsBeforeUpdate(@Req() req:any){
        this.modified_by=req.currentUser.id;
    }
} 

Problem arises in @BeforeInsert() and @BeforeUpdate() hooks where the request object is undefined. Any assistance would be greatly appreciated. Alternatively, please suggest a correct method for setting createdBy and modifiedBy columns with userId.

Answer №1

Directly accessing the request within a TypeORM entity is not possible

For more information and solutions, visit:

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

deliver a promise with a function's value

I have created a function to convert a file to base64 for displaying the file. ConvertFileToAddress(event): string { let localAddress: any; const reader = new FileReader(); reader.readAsDataURL(event.target['files'][0]); reader ...

The error message "Property 'location' is not found on type 'Readonly<{}> - React Router and Typescript" indicates that the 'location' property is not available on

I am currently working on setting up a secure route for authentication. I have implemented a ProtectedRoute component based on the documentation, which is structured like this: interface ProtectedRouteProps { auth: AuthState; } const ProtectedRoute = ( ...

What is the proper way to indicate the pointer to the current element within the array?

How can I modify a code that displays a list of posts? import React from "react"; type respX = { "id": any, "userId": any, "title": any, "body": any, } interface PropsI { } interface StateI { data: respX []; } export class Compone ...

What is the process for specifying a method on a third-party class in TypeScript?

I'm facing a challenge while trying to extend a third-party class in TypeScript. The issue is that I am unable to access any existing methods of the class within my new method. One possible solution could be to redeclare the existing methods in a sep ...

What is the most effective way to utilize getStaticPaths in a dynamic manner within next.js

There is a need to paginate static pages for each of the 3 blog categories, but the problem lies in the variable number of pages and the inability to access which category needs to be fetched in getStaticPaths. The project folder structure appears as foll ...

I encountered an error in my Node.js application stating that it could not find the name 'Userdetailshistory' array. I am puzzled as to why this error is occurring and I suspect it may be due to my

import { Component, OnInit } from '@angular/core'; import { UserdetailshistoryService } from '../../services'; @Component({ selector: 'my-userdetailshistory', templateUrl: './userdetails-history.component.html', ...

Have the quantities in the orderState been recently updated?

Whenever I modify the quantity of an order item, does it result in creating a duplicate entry for that particular item in the state every time? For instance, if the action.payload.indexNumber is 2 and action.payload.quantity is set to 100. This snippet s ...

What is the best way to generate conditional test scenarios with Protractor for testing?

Currently, there are certain test cases that I need to run only under specific conditions. it ('user can successfully log in', function() { if(siteAllowsLogin) { ..... } The problem with the above approach is that even when sitesNo ...

What is the equivalent of getElementById in .ts when working with tags in .js?

Looking to incorporate Electron, Preload, Renderer with ReactJS and TypeScript into my project. <index.html> <body> <div id="root" /> <script src='./renderer.js'/> </body> <index.ts> const root = Re ...

Using the parameter of type 'never' is necessary as per the TypeScript error message, which states that the argument of type 'string' cannot be assigned to it. This error persists even when

https://i.sstatic.net/tkX07.png const index = selectedActivities.value.indexOf(activity_id); I encountered a TypeScript error saying 'Argument of type 'string' is not assignable to parameter of type 'never'. How can I fix this iss ...

The attribute 'size' is not recognized within the data type 'string[]' (error code ts2339)

When using my Windows machine with VSCode, React/NextJS, and Typescript, a cat unexpectedly hopped onto my laptop. Once the cat left, I encountered a strange issue with my Typescript code which was throwing errors related to array methods. Below is the co ...

Exploring the return type of the `within` function in TypeScript Library

I have helpers set up for my React tests using the testing library: const getSomething = (name: string, container: Screen | any = screen) { return container.getByRole('someRole', { name: name }) } The container can be either the default screen ...

Promise rejection not handled: The play() function was unsuccessful as it requires the user to interact with the document beforehand

After upgrading my application from Angular 10 to 11, I encountered an error while running unit tests. The error causes the tests to terminate, but strangely, sometimes they run without any issues. Does anyone have suggestions on how to resolve this issue? ...

What is the best way to create buttons corresponding to the total number of "postId" properties in an array retrieved from an API call in Angular 10 using the "ngFor" directive?

export class AlphaComponent implements OnInit { apiData=[]; //array that stores API data constructor(private helpService:HelpService){ }; ngOnInit(){ this.fetchData() }; fetchData(){ this.helpService.getPostId().subscribe(( ...

Encountering Error with NodeJS Typescript: Issue with loading ES Module when running sls offline command

I have come up with a unique solution using NodeJS, Typescript, and Serverless framework to build AWS Lambdas. To debug it locally in VS Code, I use the serverless-offline library/plugin. You can find my project on GitHub here However, when I run the comm ...

"Exploring the capabilities of Rxjs ReplaySubject and its usage with the

Is it possible to utilize the pairwise() method with a ReplaySubject instead of a BehaviorSubject when working with the first emitted value? Typically, with a BehaviorSubject, I can set the initial value in the constructor allowing pairwise() to function ...

Why won't my code work with a jQuery selector?

I'm struggling to retrieve the value from a dynamically generated <div> using jQuery. It seems like the syntax I'm using doesn't recognize the div with an id tag. The HTML code is stored in a variable, and below is a snippet of code w ...

Angular provides a variety of functionality to control the behavior of elements in your application, including the

I have a page with Play, Pause, Resume, and Stop icons. When I click on the Play icon, the Pause and Stop icons are displayed. Similarly, I would like to show the Resume and Stop icons when I click on the Pause icon. I need help with this code. Thank you. ...

What is the best way to ensure an observable has finished before retrieving a value?

Looking at the function provided below: public getAssemblyTree(id: number) { .... const request = from(fetch(targetUrl.toString(), { headers: { 'responseType': 'json' }, method: 'GET' })); request.sub ...

Exploring the depths of useDispatch and dispatch in React-Redux

I am currently analyzing the code written by a former colleague of mine. Based on my understanding, useDispatch accepts an object containing the action type and payload, which is then compared to all reducers to update the state accordingly. However, in t ...