Unique and custom validation decorator within NestJS, applicably used on the service layer

I am using a subscribe function in a nestjs service to receive rabbit messages.

  @RabbitSubscribe({
    exchange: 'test'.
    routingKey: 'test',
    queue: 'q'
  })
  async handleEvent( msg: msgModel) {
    console.log(message)
  }

I have multiple subscribers set up like this and I want to implement model validation similar to what we do in controllers with validationPipe()

However, the validationPipe() or guard does not work on a simple service.

Therefore, I am looking to create a custom decorator that can validate the message received.

Something along these lines:

  @CustomDec(msg)
  @RabbitSubscribe({
    exchange: 'test'.
    routingKey: 'test',
    queue: 'q'
  })
  async handleEvent( msg: msgModel) {
    console.log(message)
  }

or 
  @RabbitSubscribe({
    exchange: 'test'.
    routingKey: 'test',
    queue: 'q'
  })
  async handleEvent( @customDec() msg: msgModel) {
    console.log(message)
  }


Is it feasible to achieve this?

Answer №1

To achieve this, you can utilize a method-decorator. Here is an example:

function MessageValidator(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value;
    descriptor.value = function (...args: any[]) {
        const messageModel = args[0];
        console.log("validating message...");
        if(messageModel.message === "isExpectedMessage") {
          console.log("OK")
        } else {
            console.log("NOK")
        }
        return originalMethod.apply(this, args);
    }
}

Implement it like so:

@RabbitSubscribe({
    exchange: 'test',
    routingKey: 'test',
    queue: 'q'
})
@MessageValidator
async handleEvent(message: messageModel) {
    console.log(message)
}

Check out the play on TypeScript playground.

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

What is the best way to retrieve the object of the selected option from a single select input in Angular

I'm currently working with an array of objects that looks like this: let myArray = [{'id':1,'Name':"ABC"},{'id':2,'Name':"XYZ"}] I'm trying to retrieve object values based on a dropdown selection, but so ...

"Dividing" a task stream/executer

Consider the following action type: interface SaveFoo { type: 'SAVE_FOO' payload: { id: string value: number } } I have a requirement to implement a saga that will apply throttling selectively. For instance, if the following actio ...

Custom objects do not return true for Symbol.hasInstance

The TypeScript playground encounters an issue with the Symbol.hasInstance built-in symbol, while it functions properly for other symbols. Testing other symbol methods such as Symbol.match and Symbol.replace show no problems, but Symbol.hasInstance is not ...

Simultaneous asynchronous access to a single object

I have been working with JS/TS for quite some time now, but the concept of race conditions still perplexes me. I am currently attempting to execute the following logic: class Deployer { protected txDataList: Array<TXData>; constructor() { this ...

What is the best way to prioritize the display of custom login buttons based on the last button used for login?

I have implemented 4 different login methods for my app, each with its own associated component. I am looking to rearrange the buttons based on the last used login method. I already have a function to determine the last login method. let lastSignedInMetho ...

Leveraging TypeScript generics for indexing

Trying to establish type information for event listeners by using generics on the .on() function. type Name = "error" | "connected"; type Callback = { error: (err: Error) => void, connected: (err: number) => void, }; function on<T exten ...

What steps can I take to set a strict boundary for displaying the address closer to the current location?

While the autocomplete feature works perfectly for me, I encountered an issue where it suggests directions away from my current location when I start typing. I came across another code snippet that uses plain JavaScript to solve this problem by setting bou ...

Page Content Fails to Load Without Reloading

I am currently working on a simple project using React with TypeScript, and I have run into an issue where the page content does not refresh as expected without having to reload the page. I am unsure of the underlying cause of this behavior. I have include ...

What is the process for obtaining an AccessToken from LinkedIn's API for Access Token retrieval?

We have successfully implemented the LinkedIn login API to generate authorization code and obtain access tokens through the browser. https://i.sstatic.net/0dfxd.png Click here for image description However, we are looking to transition this functionality ...

An unexpected issue occurred while attempting to create a new Angular app using the command ng

Currently in the process of deploying my angular application and utilizing Infragistics. Following their Documentation, I used npm install Infragistics for installation. However, when I run ng new --collection="@igniteui/angular-schematics" I e ...

Error: Trying to access the 'keyboard' property of an undefined object

I am encountering an error message 'Cannot read property 'keyboard' of undefined' and I'm not sure how to fix it. I just want to check if the keyboard is visible on the screen, but this specific line of code seems to be causing the ...

Is there a distinction in Typescript between the return types of Object.seal and .freeze?

I am looking to safeguard the constant object content from any changes during runtime. This includes alterations to both the object structure and its content. The preferred method for achieving this is by using Object.freeze. interface iRO<T> { r ...

Alert: VirtualizedList warns of slow updates for a large list despite optimized components

Struggling with avoiding the warning message "VirtualizedList: You have a large list that is slow to update" while utilizing the <FlatList> component in React-Native. Despite thorough research and attempts at finding a solution, including referencin ...

What is the best way to designate external dependencies in WebPack that are not imported using '*'?

I need assistance with specifying office-ui-fabric-react as an external dependency in my TypeScript project using Webpack. Currently, I am importing only the modules I require in my project: import { Dialog, DialogType, DialogFooter } from 'office-u ...

Ways to extract values from a javascript hash map by exclusively incorporating an array

So here's the issue I'm encountering. Let's consider the following scenario: let surfaces: Map<any, any> = new Map([{"83.1" => Object}, {"84.1" => Object}]) let arr1 = ["83.1"] This is the desired o ...

Mapped Generics in Typescript allows you to manipulate and

Currently, I am attempting to utilize TypeScript generics in order to transform them into a new object structure. Essentially, my goal is to change: { key: { handler: () => string }, key2: { hander: () => number }, } to: ...

Converting a string to an HTML object in Angular using Typescript and assigning it to a variable

I am facing an issue with passing HTML content from a service to a div element. I have a function that fetches HTML content as a string from a file and converts it into an HTML object, which I can see working in the console. However, when trying to assign ...

Uncover the value type of a key in TypeScript without using a discriminated union

I want to implement a type map that ensures the type of an object's value for a specific key is determined by the value of another key. For example: type CurrencyValue = { code: string; value: number; }; type FieldMap = { text: string; curren ...

Checking for String Const Type in TypeScript

In my code, I have a custom type called Admin with two possible values: 'ADMIN' or 'AGENT'. There is a function that retrieves the user role from local storage: return localStorage.getItem('role'); I am looking to verify if ...

Tips for programmatically focusing on a v-textarea using Vuetify and TypeScript

It feels impossible right now, I've attempted some unconventional methods like: (this.refs.vtextarea as any).textarea.focus() ((this.refs.vtextarea as Vue).$el as HTMLElement).focus() and so on... Javascript source code is quite complex for me to ...