Bird
0
0

Why does this guard fail to read metadata?

medium📝 Debug Q7 of 15
NestJS - Guards
Why does this guard fail to read metadata?
const roles = this.reflector.get('roles', context.getClass());

Given that the metadata was set on the method using @SetMetadata('roles', ['admin']).
ABecause metadata was set on the method, but get is called on the class
BBecause the key 'roles' is misspelled
CBecause Reflector.get requires a third argument
DBecause context.getClass() returns undefined
Step-by-Step Solution
Solution:
  1. Step 1: Understand metadata scope

    Metadata set on a method is not available on the class level, so calling get with context.getClass() returns undefined.
  2. Step 2: Check other options

    The key is correct, Reflector.get does not require a third argument, and context.getClass() returns the class.
  3. Final Answer:

    Because metadata was set on the method, but get is called on the class -> Option A
  4. Quick Check:

    Metadata scope must match get target = B [OK]
Quick Trick: Match metadata set location with Reflector.get target [OK]
Common Mistakes:
  • Calling get on class when metadata is on method
  • Assuming Reflector.get needs extra arguments
  • Misunderstanding context.getClass()

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes