Bird
Raised Fist0
NestJSframework~20 mins

Decorator-based architecture in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
NestJS Decorator Master
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 NestJS controller method?
Consider this NestJS controller method decorated with @Get and @UseGuards. What will be the HTTP response status code when this endpoint is accessed successfully?
NestJS
import { Controller, Get, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Controller('items')
export class ItemsController {
  @Get()
  @UseGuards(AuthGuard('jwt'))
  findAll() {
    return { message: 'Items fetched' };
  }
}
A200 OK with JSON { message: 'Items fetched' }
B401 Unauthorized error
C404 Not Found error
D500 Internal Server Error
Attempts:
2 left
💡 Hint
Think about what @UseGuards(AuthGuard('jwt')) does when the user is authenticated.
📝 Syntax
intermediate
2:00remaining
Which option correctly applies a custom decorator to inject a user object in NestJS?
You want to create a custom decorator @CurrentUser() that extracts the user from the request object. Which option correctly defines and uses this decorator in a controller method?
NestJS
import { createParamDecorator, ExecutionContext } from '@nestjs/common';

export const CurrentUser = createParamDecorator((data: unknown, ctx: ExecutionContext) => {
  const request = ctx.switchToHttp().getRequest();
  return request.user;
});

@Controller('profile')
export class ProfileController {
  @Get()
  getProfile(@CurrentUser() user) {
    return user;
  }
}
ACorrect as shown in the code above
BReplace createParamDecorator with @Injectable decorator
CUse @Param('user') instead of @CurrentUser()
DDefine CurrentUser as a class instead of a function
Attempts:
2 left
💡 Hint
Custom parameter decorators use createParamDecorator function.
🔧 Debug
advanced
2:00remaining
Why does this NestJS service fail to inject the repository?
Given this service code, why will NestJS throw a runtime error about missing dependencies?
NestJS
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';

@Injectable()
export class UserService {
  constructor(@InjectRepository(User) private userRepository: Repository<User>) {}

  findAll() {
    return this.userRepository.find();
  }
}
AThe findAll method is missing async keyword
BThe @Injectable decorator is missing
CThe User entity is not imported correctly
DThe constructor parameter is missing @InjectRepository(User) decorator
Attempts:
2 left
💡 Hint
Check how TypeORM repositories are injected in NestJS services.
❓ lifecycle
advanced
2:00remaining
What happens when a NestJS provider implements OnModuleInit?
If a service class implements the OnModuleInit interface and defines the onModuleInit() method, when is this method called?
NestJS
import { Injectable, OnModuleInit } from '@nestjs/common';

@Injectable()
export class AppService implements OnModuleInit {
  onModuleInit() {
    console.log('Module initialized');
  }
}
ACalled every time a request is received
BCalled once after the module's providers are initialized
CCalled only when the application shuts down
DCalled before the module's providers are created
Attempts:
2 left
💡 Hint
Think about the lifecycle of modules and providers in NestJS.
🧠 Conceptual
expert
2:00remaining
Which option best describes the role of decorators in NestJS architecture?
In NestJS, decorators like @Controller, @Injectable, and @Module are used extensively. What is their primary purpose in the framework's architecture?
AThey execute code immediately to modify class behavior at runtime
BThey replace the need for writing any configuration files
CThey add metadata to classes and methods to enable dependency injection and routing
DThey automatically generate database schemas from classes
Attempts:
2 left
💡 Hint
Think about how NestJS uses decorators to organize and connect parts of the app.

Practice

(1/5)
1. In NestJS, what is the main purpose of using decorators like @Controller() and @Injectable()?
easy
A. To replace the need for writing any class methods
B. To execute the class methods automatically on app start
C. To mark classes with specific roles and add metadata for NestJS to manage
D. To style the output of the application in the browser

Solution

  1. Step 1: Understand decorator roles in NestJS

    Decorators like @Controller() and @Injectable() add metadata to classes, telling NestJS their purpose.
  2. Step 2: Recognize how NestJS uses this metadata

    NestJS uses this metadata to organize and manage components like controllers and services during runtime.
  3. Final Answer:

    To mark classes with specific roles and add metadata for NestJS to manage -> Option C
  4. Quick Check:

    Decorators add metadata = C [OK]
Hint: Decorators label classes for NestJS to organize [OK]
Common Mistakes:
  • Thinking decorators run methods automatically
  • Confusing decorators with styling tools
  • Believing decorators remove the need for methods
2. Which of the following is the correct way to define a controller class in NestJS using decorators?
easy
A. @Controller() class MyController { }
B. class MyController { }
C. function Controller() { } class MyController { }
D. @Injectable() class MyController { }

Solution

  1. Step 1: Recall the syntax for controller decorators

    In NestJS, the @Controller() decorator is placed immediately before the class definition.
  2. Step 2: Check each option for correct decorator usage

    @Controller() class MyController { } correctly shows @Controller() before the class. class MyController { } lacks any decorator. function Controller() { } class MyController { } incorrectly defines a function instead of using a decorator. @Injectable() class MyController { } uses @Injectable() which is for services, not controllers.
  3. Final Answer:

    @Controller() class MyController { } -> Option A
  4. Quick Check:

    Controller decorator before class = B [OK]
Hint: Controller classes need @Controller() decorator above class [OK]
Common Mistakes:
  • Omitting the decorator entirely
  • Using @Injectable() instead of @Controller()
  • Trying to define decorators as functions
3. Given the following NestJS controller code, what will be the output when a GET request is made to '/hello'?
@Controller('hello')
export class HelloController {
  @Get()
  greet() {
    return 'Hello, NestJS!';
  }
}
medium
A. "Hello, NestJS!"
B. 404 Not Found error
C. An empty response
D. A runtime error due to missing decorator

Solution

  1. Step 1: Analyze the route and method decorators

    The @Controller('hello') sets the base path to '/hello'. The @Get() decorator on greet() means this method handles GET requests to '/hello'.
  2. Step 2: Understand the method return value

    The greet() method returns the string 'Hello, NestJS!'. So, a GET request to '/hello' returns this string as the response.
  3. Final Answer:

    "Hello, NestJS!" -> Option A
  4. Quick Check:

    GET /hello returns method string = A [OK]
Hint: Match @Controller path with @Get method for output [OK]
Common Mistakes:
  • Assuming 404 because of missing route
  • Expecting JSON instead of string
  • Thinking decorators cause runtime errors here
4. Identify the error in the following NestJS service code:
@Injectable
export class UserService {
  getUser() {
    return { name: 'Alice' };
  }
}
medium
A. Return value must be a string, not an object
B. Missing parentheses in @Injectable decorator
C. Class name should be UserServices
D. Method getUser() should be async

Solution

  1. Step 1: Check the decorator syntax

    The @Injectable decorator requires parentheses even if no arguments are passed, so it should be @Injectable().
  2. Step 2: Verify other code parts

    The method getUser() can be synchronous and return an object. Class name and return type are valid as is.
  3. Final Answer:

    Missing parentheses in @Injectable decorator -> Option B
  4. Quick Check:

    @Injectable() needs parentheses = D [OK]
Hint: Always add () after @Injectable even if empty [OK]
Common Mistakes:
  • Omitting parentheses on decorators
  • Thinking methods must be async
  • Changing class names unnecessarily
5. You want to create a NestJS controller that handles GET requests to '/users/:id' and returns the user ID from the URL. Which of the following code snippets correctly uses decorators to achieve this?
hard
A.
@Controller('users')
export class UserController {
  @Get(':id')
  getUser(id: string) {
    return `User ID is ${id}`;
  }
}
B.
@Controller('users')
export class UserController {
  @Get()
  getUser(@Body('id') id: string) {
    return `User ID is ${id}`;
  }
}
C.
@Controller('users')
export class UserController {
  @Post(':id')
  getUser(@Param('id') id: string) {
    return `User ID is ${id}`;
  }
}
D.
@Controller('users')
export class UserController {
  @Get(':id')
  getUser(@Param('id') id: string) {
    return `User ID is ${id}`;
  }
}

Solution

  1. Step 1: Identify the correct HTTP method and route parameter usage

    The route is '/users/:id' and should respond to GET requests, so @Get(':id') is correct.
  2. Step 2: Check parameter decorator usage

    The method parameter must use @Param('id') to extract the 'id' from the URL path.
    @Controller('users')
    export class UserController {
      @Get(':id')
      getUser(@Param('id') id: string) {
        return `User ID is ${id}`;
      }
    }
    does this correctly.
  3. Step 3: Verify other options

    @Controller('users')
    export class UserController {
      @Get()
      getUser(@Body('id') id: string) {
        return `User ID is ${id}`;
      }
    }
    uses @Body('id') which reads from request body, not URL.
    @Controller('users')
    export class UserController {
      @Post(':id')
      getUser(@Param('id') id: string) {
        return `User ID is ${id}`;
      }
    }
    uses POST instead of GET.
    @Controller('users')
    export class UserController {
      @Get(':id')
      getUser(id: string) {
        return `User ID is ${id}`;
      }
    }
    misses the @Param decorator, so 'id' won't be injected.
  4. Final Answer:

    The code snippet with @Get(':id') and @Param('id') -> Option D
  5. Quick Check:

    GET + @Param('id') for URL param = A [OK]
Hint: Use @Get(':id') and @Param('id') to get URL parameters [OK]
Common Mistakes:
  • Using @Body instead of @Param for URL params
  • Using wrong HTTP method decorator
  • Forgetting @Param decorator on method argument
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