Controller Internals

Preview — 3 of 10 questions

Inside a guard you need to read metadata set by @Roles('admin') on the handler. Which Reflector call retrieves it?

javascript
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    const roles = this.reflector.get<string[]>('roles', context.getHandler());
    return !roles || roles.includes('admin');
  }
}
Athis.reflector.get('roles', context.getRequest())
Bthis.reflector.resolve('roles')
CReflect.getMetadata('roles', context)
Dthis.reflector.get<string[]>('roles', context.getHandler())

When the same metadata key is set on both the controller class and the method, which Reflector method makes the method-level value win?

javascript
const role = this.reflector.getAllAndOverride<string>('role', [
  context.getHandler(), // checked first → wins if present
  context.getClass(),
]);
AgetAllAndOverride([handler, class])
BgetAllAndMerge([handler, class])
Cget(key, class)
DgetAll([class, handler])

You want a @Report() decorator that behaves like @Get('report') plus sets metadata. What underlying mechanism do the built-in method decorators use that you can reuse?

javascript
import { applyDecorators, Get, SetMetadata } from '@nestjs/common';

export function Report() {
  return applyDecorators(Get('report'), SetMetadata('audit', true));
}
// usage: @Report() generate() {}
AThey require a separate @RegisterRoute() call in the module
BThey monkey-patch the Express router at import time
CThey register routes by writing to a global array
DThey call applyDecorators(RequestMapping(...))-style metadata via @nestjs/common internals (RequestMapping/Reflect.defineMetadata)

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.