0
0
NestJSframework~10 mins

Guard interface (canActivate) in NestJS - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to implement the canActivate method in a NestJS guard.

NestJS
canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
  return [1];
}
Drag options to blanks, or click blank then click option'
Atrue
Bfalse
Cnull
Dundefined
Attempts:
3 left
💡 Hint
Common Mistakes
Returning false blocks access.
Returning null or undefined causes errors.
2fill in blank
medium

Complete the code to extract the request object inside canActivate using ExecutionContext.

NestJS
const request = context.switchToHttp().[1]();
Drag options to blanks, or click blank then click option'
AgetResponse
BgetNext
CgetRequest
DgetHandler
Attempts:
3 left
💡 Hint
Common Mistakes
Using getResponse instead of getRequest.
Trying to access request directly without switchToHttp.
3fill in blank
hard

Fix the error in the guard method to correctly check if user is authenticated.

NestJS
const user = request.user;
if (!user) {
  throw new [1]('Unauthorized');
}
return true;
Drag options to blanks, or click blank then click option'
AForbiddenException
BUnauthorizedException
CBadRequestException
DNotFoundException
Attempts:
3 left
💡 Hint
Common Mistakes
Throwing ForbiddenException instead of UnauthorizedException.
Not throwing any exception and returning false.
4fill in blank
hard

Fill both blanks to create a guard that allows access only if user role is 'admin'.

NestJS
const user = request.user;
return user?.role [1] [2];
Drag options to blanks, or click blank then click option'
A===
B!==
C'admin'
D'user'
Attempts:
3 left
💡 Hint
Common Mistakes
Using !== instead of ===.
Comparing to 'user' instead of 'admin'.
5fill in blank
hard

Fill all three blanks to implement a guard that checks if request method is POST and user is authenticated.

NestJS
const request = context.switchToHttp().getRequest();
if (request.method [1] 'POST' && request.user [2] null) {
  return [3];
}
return false;
Drag options to blanks, or click blank then click option'
A===
B!==
Ctrue
Dfalse
Attempts:
3 left
💡 Hint
Common Mistakes
Using == instead of ===.
Checking user === null instead of !== null.
Returning false instead of true when conditions met.