I think a Custom Class decorator would be the solution for this.
1. Define the Decorator
First, create a new file for your custom decorator. Let's call it custom-class.decorator.ts.
typescript
import { SetMetadata } from '@nestjs/common';
export const CustomClass = (value: string): ClassDecorator => {
return SetMetadata('customClassKey', value);
};
Here, SetMetadata is used to attach metadata to the class.
2. Apply the Custom Decorator
Apply this decorator to any class where you want to use it.
typescript
import { CustomClass } from './custom-class.decorator';
@CustomClass('myCustomValue')
export class ExampleService {
// Your class logic here
}
3. Access the Metadata
To access this metadata, use the Reflector service in a guard, interceptor, or another provider.
typescript
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
@Injectable()
export class CustomGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const customValue = this.reflector.get<string>(
'customClassKey',
context.getClass(),
);
if (!customValue) {
return true;
}
// Add your custom logic here
console.log(`Custom value from decorator: ${customValue}`);
return true;
}
}
4. Register the Guard
Finally, apply the guard either globally, at the module level, or at the route level.
typescript
import { Module } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import { ExampleService } from './example.service';
import { CustomGuard } from './custom.guard';
@Module({
providers: [
ExampleService,
{
provide: APP_GUARD,
useClass: CustomGuard,
},
],
})
export class AppModule
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I think a Custom Class decorator would be the solution for this.