Guide to crafting a personalized parameter decorator for extracting the user from a request

Within my express.js application, I have set up an endpoint where I extract the user from the request as shown below:

@Put('/:_id')
async update (@Request() req: express.Request) {
  // @ts-ignore
  const user = req.user;
  ....
}

I am interested in creating a custom Parameter Decorator to easily retrieve the user using @GetUser user, which would allow my endpoint to appear like the example below:

@Put('/:_id')
async update (@GetUser user: any) {
  // We can now directly use the user object 
  ....
}

Upon investigating, I found out that I can develop a custom Parameter Decorator by implementing the following code snippet:

export function GetUser(
  target: Object,
  propertyKey: string,
  parameterIndex: number
) {
  console.log(`Decorating param ${parameterIndex} from ${propertyKey}`);
 }

The question arises on how to access the request within this custom Parameter Decorator to fetch the user?

Answer №1

After digging into the same topic, I found out that the @Request decorator has the ability to accept additional parameters.

If you're interested, you can check out the related Github issue here: https://github.com/serhiisol/node-decorators/issues/27

To utilize this feature, simply include the parameter name (such as user) within the @Request decorator like demonstrated in the example below:

@Put('/:_id')
async update (@Request('user') user: UserType) {
  ....
}

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

Send a string to directive via HTML

Trying to implement a "clipboard" directive following this example. In my case, I need to dynamically compute the string to be copied to the clipboard. The goal is to pass the output of a function that generates the string to the directive. Currently, I ...

The route param is throwing a "Cannot read property 'name' of undefined" error, indicating that the property

Currently, I am enrolled in an ExpressJS course on TUTS+ From the video tutorial, I have implemented the following code snippet (excerpt from video): var express = require('express'), app = express(); app.get('/name/:name', funct ...

Mastering Authentication in React JS: Best Practices

I am currently working on integrating Backend (Express JS) and Frontend (React JS). One of the challenges I am facing is understanding how to manage sessions effectively. When a user logs in using a form built with React JS, the backend responds with a HS ...

How to Define Intersection Type with Symbol in TypeScript?

I'm currently working on a helper function that associates a Symbol with a value. function setCustomSymbol<S extends symbol, T>(symbol: S, data: T, defaultValue: any = true): S & T { /*...*/ } The issue I'm facing is trying to instruc ...

Transmitting files instantly without the need for a response body

Currently, Express is serving index.html file by default even though I haven't specified the response body yet. This is how my file structure looks: node_modules public img abc.html index.html script.js ...

Setting headers in Node using express-http-proxy before proxying data is an effective way to customize

When attempting to proxy to a specific address, I need to set the header of the proxy beforehand. It's like an interceptor for me. Currently, I am using the express-http-library and express with Node.JS. However, my code so far doesn't seem to be ...

Accessing a single Express app can result in the session being terminated in another app on the same server

On a single server machine, I have two Express 4.x applications running on different ports but sharing the same MongoDB instance. Each app uses its own database and session secret. When logging into either application A or B individually, everything works ...

Tips for properly handling a property that receives its value from a callback function and waiting for it to be updated

Below is my TypeScript code: private getInfoSystem = () => { this.systemInfo = { cpuSpeed: 0 , totalRam: os.totalmem(), freeRam: os.freemem(), sysUpTime: os_utils.sysUptime(), loadAvgMinutes: { on ...

typescript: the modules with relational paths could not be located

As part of a migration process, I am currently converting code from JavaScript to TypeScript. In one of my files 'abc.ts', I need to import the 'xyz.css' file, which is located in the same directory. However, when I try to import it usi ...

Is there a specific type required for the Vue `install` function? Is it necessary to have the `directive` property on the `Vue`

I've been working on implementing a Vue directive in typescript, but I'm struggling to determine the correct types to use for the Vue install function. Using install(Vue: any): void feels a bit strange to me. I attempted importing Vue and using ...

Rule of authentication using Firebase Database

I need to establish a rule in my Firebase Database to prevent unauthorized access for reading and writing purposes. Within my database, there is a collection of words, each containing a "uid" field that corresponds with the uid of the authUser key stored ...

display the picture depending on the circumstances

Is there a way for the image tag to display different images based on a condition? I attempted the code below, but it's not displaying the image: <img src="{{row.image}}!=null?'data:image/jpeg;base64,{{row.image}}':'./assets/img/qu ...

Utilizing Websockets in Node JS and Express with Heroku can lead to issues when adding new routes, causing disruptions in

Welcome to my first Stack Overflow post! As a beginner in Node.js, I am seeking assistance while working on the Heroku tutorial mentioned here: https://devcenter.heroku.com/articles/node-websockets (option 1) I am developing an application that utilizes ...

What is the best way to associate dates with a particular ID within a textfield's value?

I am working with an array of objects called dates, and each object in the array looks like this: {id: 9898, date: 10/06/2020}. Within this array, there are multiple objects with the same id, and I want to display dates with the same id in a TextField com ...

When defining a stripe in TypeScript using process.env.STRIPE_SECRET_KEY, an error of "string | undefined" is encountered

Every time I attempt to create a new stripe object, I encounter the error message "Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string& ...

Get your hands on the latest version of Excel for Angular

214/5000 I am currently facing an issue in Angular where I am attempting to generate an excel file. Within the file, there is a "Day" column that is meant to display numbers 1 through 31. However, when attempting this, only the last number (31) is being pr ...

Using Node.js and TypeScript to define custom data types has become a common practice among developers

I offer a variety of services, all yielding the same outcome: type result = { success: boolean data?: any } const serviceA = async (): Promise<result> => { ... } const serviceB = async (): Promise<result> => { ... } However, th ...

Cannot find property '' within type 'never'. (Using TypeScript useState with mapped JSON data from a server)

Currently, I am following a tutorial on using React with Material-UI and decided to add TypeScript into the mix. If you're interested, here is the link: Net ninja MUI The file Notes.tsx contains the code for fetching data from a JSON server and then ...

Issues with the execution of Typescript decorator method

Currently, I'm enrolled in the Mosh TypeScript course and came across a problem while working on the code. I noticed that the code worked perfectly in Mosh's video tutorial but when I tried it on my own PC and in an online playground, it didn&apo ...

Issue: [Issue: ENOENT: the file or directory './1695556319341.mp3' does not exist]

I am currently facing an issue while trying to convert an mp4 file to an mp3 file and then uploading it directly to Firebase storage without saving it locally on my machine. The error I encounter is "Error: [Error: ENOENT: no such file or directory, open ...