Complete the code to create a custom decorator that sets metadata with the key 'role'.
import { SetMetadata } from '@nestjs/common'; export const Roles = (role: string) => SetMetadata('[1]', role);
The metadata key used in NestJS examples for roles is usually 'roles'. This key is used later to retrieve the metadata.
Complete the code to inject Reflector in a guard constructor.
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common'; import { Reflector } from '@nestjs/core'; @Injectable() export class RolesGuard implements CanActivate { constructor(private readonly [1]: Reflector) {} canActivate(context: ExecutionContext): boolean { // guard logic return true; } }
The injected Reflector instance is usually named 'reflector' in the constructor for clarity and convention.
Fix the error in retrieving metadata inside the guard using Reflector.
const roles = this.reflector.get<string[]>('[1]', context.getHandler());
The metadata key must match the one used in the custom decorator, which is 'roles'.
Fill both blanks to create a custom decorator and retrieve metadata in a guard.
export const Roles = (role: string) => SetMetadata([1], role); const roles = this.reflector.get<string[]>([2], context.getHandler());
Both the decorator and the reflector must use the same metadata key 'roles' to work correctly.
Fill all three blanks to create a guard that checks roles metadata and returns access decision.
canActivate(context: ExecutionContext): boolean {
const roles = this.reflector.get<string[]>([1], context.getHandler());
if (!roles) {
return [2];
}
const request = context.switchToHttp().getRequest();
const user = request.user;
return roles.some(role => user.roles?.includes([3]));
}The guard retrieves 'roles' metadata, returns true if no roles are set, and checks if the user has any required role.