NestJS · Middle · Question 9 of 75
How do you write a custom parameter decorator like @User()?
export const User = createParamDecorator((data: unknown, ctx: ExecutionContext) => {
return ctx.switchToHttp().getRequest().user;
});- 1With
@Injectable()on a function - 2It's impossible; only built-in decorators exist
- ✓Correct answer: With
createParamDecorator, which reads from the execution context and returns the value for the parameter
Explanation
Custom decorators can also accept data (@User('email')) and be combined with pipes, e.g. @User(new ValidationPipe()).