Bird
0
0

Identify the error in this custom decorator usage and how to fix it:

medium📝 Debug Q14 of 15
NestJS - Guards
Identify the error in this custom decorator usage and how to fix it:
import { SetMetadata } from '@nestjs/common';

function Permissions(permissions: string[]) {
  return (target: any, key: string) => {
    Reflect.defineMetadata('permissions', permissions, target, key);
  };
}

class UserController {
  @Permissions(['read'])
  getUser() {
    return 'user';
  }
}
AThe decorator must be applied to the class, not method
BThe decorator is missing the return type annotation
CThe decorator should use SetMetadata instead of Reflect.defineMetadata
DThe decorator function parameters are incorrect; should include descriptor
Step-by-Step Solution
Solution:
  1. Step 1: Check decorator implementation

    The decorator manually calls Reflect.defineMetadata, which works but is not recommended in NestJS.
  2. Step 2: Use NestJS helper for consistency

    SetMetadata is the standard NestJS helper that wraps Reflect.defineMetadata and ensures compatibility with Reflector and other NestJS internals.
  3. Final Answer:

    The decorator should use SetMetadata instead of Reflect.defineMetadata -> Option C
  4. Quick Check:

    Use SetMetadata for custom decorators in NestJS [OK]
Quick Trick: Always use SetMetadata helper for custom decorators [OK]
Common Mistakes:
  • Using Reflect.defineMetadata directly instead of SetMetadata
  • Ignoring NestJS decorator conventions
  • Misunderstanding decorator parameters

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes