Bird
Raised Fist0
NestJSframework~20 mins

Reflector and custom decorators in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Reflector and Decorators Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this custom decorator usage?
Consider this NestJS custom decorator and its usage in a controller method. What will the Reflector retrieve as metadata value?
NestJS
import { SetMetadata, Reflector } from '@nestjs/common';

const Roles = (...roles: string[]) => SetMetadata('roles', roles);

class SampleController {
  @Roles('admin', 'user')
  getData() {
    return 'data';
  }
}

const reflector = new Reflector();
const metadata = reflector.get('roles', SampleController.prototype.getData);
console.log(metadata);
Anull
Bundefined
C['roles']
D['admin', 'user']
Attempts:
2 left
💡 Hint
Think about what SetMetadata stores and how Reflector retrieves it.
📝 Syntax
intermediate
2:00remaining
Which option correctly defines a custom decorator that sets metadata 'permission'?
You want to create a custom decorator named Permission that sets metadata key 'permission' with a string value. Which code snippet is correct?
Aexport const Permission = (perm: string) => Reflect.defineMetadata('permission', perm);
Bexport function Permission(perm: string) { return Reflect.metadata('permission', perm); }
Cexport const Permission = (perm: string) => SetMetadata('permission', perm);
Dexport function Permission(perm: string) { SetMetadata('permission', perm); }
Attempts:
2 left
💡 Hint
Remember that SetMetadata returns a decorator function.
🔧 Debug
advanced
2:00remaining
Why does Reflector.get return undefined in this code?
Given this code snippet, why does the Reflector return undefined when trying to get 'roles' metadata?
NestJS
import { SetMetadata, Reflector } from '@nestjs/common';

const Roles = (...roles: string[]) => SetMetadata('roles', roles);

class UserController {
  @Roles('admin')
  getUser() {
    return 'user';
  }
}

const reflector = new Reflector();
const metadata = reflector.get('roles', UserController.getUser);
console.log(metadata);
ABecause the 'roles' key is misspelled in the decorator.
BBecause UserController.getUser is undefined; method should be accessed via prototype.
CBecause Reflector requires the class instance, not the method reference.
DBecause SetMetadata does not attach metadata to methods, only classes.
Attempts:
2 left
💡 Hint
Check how methods are accessed on classes vs prototypes.
🧠 Conceptual
advanced
1:30remaining
What is the main purpose of the Reflector class in NestJS?
Choose the best description of what the Reflector class does in NestJS.
AIt reads metadata set by decorators on classes and methods at runtime.
BIt automatically applies decorators to controller methods.
CIt compiles TypeScript decorators into JavaScript functions.
DIt manages dependency injection container instances.
Attempts:
2 left
💡 Hint
Think about how metadata is accessed after decorators run.
❓ state_output
expert
2:30remaining
What is the output of this custom decorator and Reflector usage with inheritance?
Given these classes and decorators, what will the Reflector return for 'roles' metadata on ChildController.getData?
NestJS
import { SetMetadata, Reflector } from '@nestjs/common';

const Roles = (...roles: string[]) => SetMetadata('roles', roles);

class ParentController {
  @Roles('admin')
  getData() {
    return 'parent data';
  }
}

class ChildController extends ParentController {
  getData() {
    return 'child data';
  }
}

const reflector = new Reflector();
const metadata = reflector.get('roles', ChildController.prototype.getData);
console.log(metadata);
Aundefined
Bnull
C[]
D['admin']
Attempts:
2 left
💡 Hint
Consider how metadata is attached and whether it is inherited by overridden methods.

Practice

(1/5)
1. What is the primary purpose of the Reflector class in NestJS when used with custom decorators?
easy
A. To read metadata set by custom decorators on classes or methods
B. To create new decorators dynamically at runtime
C. To replace the default routing mechanism in controllers
D. To automatically validate request payloads

Solution

  1. Step 1: Understand Reflector's role

    The Reflector class is designed to read metadata that custom decorators attach to classes or methods.
  2. Step 2: Differentiate from other functions

    It does not create decorators, change routing, or validate payloads; it only reads metadata.
  3. Final Answer:

    To read metadata set by custom decorators on classes or methods -> Option A
  4. Quick Check:

    Reflector reads metadata = D [OK]
Hint: Reflector always reads metadata, never creates or changes routes [OK]
Common Mistakes:
  • Thinking Reflector creates decorators
  • Confusing Reflector with validation tools
  • Assuming Reflector changes routing behavior
2. Which of the following is the correct way to define a custom decorator that sets metadata with key 'roles' and value passed as argument?
easy
A. export function Roles() { return SetMetadata('roles'); }
B. export function Roles(roles: string[]) { return Reflect.metadata('roles', roles); }
C. export const Roles = (roles: string[]) => Reflector.set('roles', roles);
D. export const Roles = (roles: string[]) => SetMetadata('roles', roles);

Solution

  1. Step 1: Recall SetMetadata usage

    SetMetadata is the NestJS helper to create decorators that attach metadata with a key and value.
  2. Step 2: Check each option

    export const Roles = (roles: string[]) => SetMetadata('roles', roles); correctly returns SetMetadata with key 'roles' and the passed roles array. export function Roles(roles: string[]) { return Reflect.metadata('roles', roles); } uses Reflect.metadata which is not standard in NestJS. export const Roles = (roles: string[]) => Reflector.set('roles', roles); incorrectly calls Reflector.set which does not exist. export function Roles() { return SetMetadata('roles'); } calls SetMetadata without value, which is invalid.
  3. Final Answer:

    export const Roles = (roles: string[]) => SetMetadata('roles', roles); -> Option D
  4. Quick Check:

    SetMetadata creates decorators with key-value metadata = A [OK]
Hint: Use SetMetadata(key, value) to create custom decorators [OK]
Common Mistakes:
  • Using Reflector to set metadata instead of reading
  • Omitting the value argument in SetMetadata
  • Using Reflect.metadata instead of SetMetadata
3. Given this code snippet, what will be logged when accessing the getData method?
import { Controller, Get, UseGuards, SetMetadata } from '@nestjs/common';
import { Reflector } from '@nestjs/core';

const Roles = (roles: string[]) => SetMetadata('roles', roles);

@Controller('items')
export class ItemsController {
  @Get()
  @Roles(['admin'])
  getData() {
    return 'secret data';
  }
}

// In a guard:
const reflector = new Reflector();
const roles = reflector.get<string[]>('roles', ItemsController.prototype.getData);
console.log(roles);
medium
A. ['admin']
B. undefined
C. An error because metadata key is missing
D. [] (empty array)

Solution

  1. Step 1: Understand metadata retrieval context

    Reflector.get requires the target object and the property key (method name as string) to read metadata.
  2. Step 2: Analyze the call

    The code calls reflector.get with ItemsController.prototype.getData as the second argument, which is a function, not the method name string 'getData'. This causes Reflector to fail to find metadata and return undefined.
  3. Final Answer:

    undefined -> Option B
  4. Quick Check:

    Reflector.get needs method name string, else returns undefined [OK]
Hint: Pass method name as string to Reflector.get to read metadata [OK]
Common Mistakes:
  • Passing method function instead of method name string
  • Expecting metadata on class prototype instead of method
  • Assuming metadata always returns array
4. 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';
  }
}
medium
A. The decorator must be applied to the class, not method
B. The decorator is missing the return type annotation
C. The decorator should use SetMetadata instead of Reflect.defineMetadata
D. The decorator function parameters are incorrect; should include descriptor

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]
Hint: Always use SetMetadata helper for custom decorators [OK]
Common Mistakes:
  • Using Reflect.defineMetadata directly instead of SetMetadata
  • Ignoring NestJS decorator conventions
  • Misunderstanding decorator parameters
5. You want to create a guard that allows access only if the user has at least one role from the @Roles decorator metadata. Which approach correctly uses Reflector and the custom decorator to achieve this?
hard
A. Use Reflector.getAllAndOverride('roles', [context.getHandler(), context.getClass()]) to get roles, then check user roles against it
B. Use Reflector.get('roles', context.getHandler()) only, ignoring class-level metadata
C. Manually parse request headers for roles instead of using Reflector
D. Use Reflector.set('roles', roles) inside the guard to assign roles dynamically

Solution

  1. Step 1: Understand metadata inheritance

    Roles can be set on method or class level. To get effective roles, use Reflector.getAllAndOverride which checks method first, then class.
  2. Step 2: Implement guard logic

    Retrieve roles with getAllAndOverride, then compare with user's roles to allow or deny access.
  3. Final Answer:

    Use Reflector.getAllAndOverride('roles', [context.getHandler(), context.getClass()]) to get roles, then check user roles against it -> Option A
  4. Quick Check:

    getAllAndOverride merges metadata from method and class [OK]
Hint: Use getAllAndOverride to combine method and class metadata [OK]
Common Mistakes:
  • Ignoring class-level metadata roles
  • Trying to set metadata inside guard
  • Not using Reflector to read metadata
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard