Discover how to stop struggling with messy URL parsing and make your API code shine!
Why Query parameters in NestJS? - Purpose & Use Cases
Imagine building a web API where you manually parse the URL string to get filter or sort options every time a user requests data.
Manually extracting query parameters is error-prone, repetitive, and makes your code messy. It's easy to forget validation or handle missing values incorrectly.
NestJS provides built-in support to automatically extract and validate query parameters, making your code cleaner and safer.
const url = req.url; const filter = url.split('?')[1]?.split('=')[1];
@Get() getItems(@Query('filter') filter: string) { return this.service.find(filter); }
You can easily build flexible APIs that accept user input through URLs without messy parsing code.
Allowing users to filter a product list by category or price range using query parameters like ?category=books&maxPrice=20.
Manual parsing of query parameters is tedious and error-prone.
NestJS simplifies extracting and validating query parameters.
This leads to cleaner, safer, and more maintainable API code.
Practice
@Query() decorator in a NestJS controller?Solution
Step 1: Understand the role of
The@Query()@Query()decorator extracts query parameters from the URL in a GET request.Step 2: Compare with other decorators
Other decorators like@Body()handle POST bodies, and@Param()handles route params, so they don't fit here.Final Answer:
To access query parameters sent in the URL -> Option DQuick Check:
@Query()reads URL queries = A [OK]
@Query() reads URL query strings [OK]- Confusing
@Query()with@Body() - Thinking
@Query()defines routes - Using
@Query()to inject services
page in a NestJS controller method?Solution
Step 1: Identify correct decorator usage
To get a specific query parameter, use@Query('paramName')syntax.Step 2: Check syntax correctness
async getItems(@Query('page') page: number) {} uses@Query('page')correctly. Options A and C use wrong decorators, and D has invalid syntax.Final Answer:
async getItems(@Query('page') page: number) {} -> Option CQuick Check:
Use@Query('param')for query params = B [OK]
@Query('name') to get specific query param [OK]- Using
@Param()instead of@Query() - Trying to access query param as
@Query.page - Using
@Body()for query parameters
async find(@Query() query) {
return query.page + '-' + query.limit;
}What will be the output if the URL is
/items?page=2&limit=5?Solution
Step 1: Understand
The@Query()behavior@Query()decorator without arguments returns an object with all query parameters as strings.Step 2: Check the returned string concatenation
With URL?page=2&limit=5,query.pageis "2" andquery.limitis "5". Concatenation returns "2-5".Final Answer:
"2-5" -> Option AQuick Check:
Query object has keys = "2-5" [OK]
@Query() gets all query params as object [OK]- Expecting numbers instead of strings from query params
- Assuming
@Query()returns undefined - Thinking it causes runtime error
search?:async search(@Query(search) searchTerm: string) {
return searchTerm;
}Solution
Step 1: Check
The argument to@Querydecorator syntax@Query()must be a string literal naming the query parameter, e.g.,@Query('search').Step 2: Identify the error in the code
The code uses@Query(search)without quotes, which is invalid syntax and causes an error.Final Answer:
The@Querydecorator argument should be a string:@Query('search')-> Option BQuick Check:
Decorator argument must be string literal = D [OK]
@Query('name') [OK]- Forgetting quotes around query param name
- Using
@Param()for query params - Thinking async keyword is disallowed
sort and filter. If filter is missing, it should default to "all". Which code snippet correctly implements this behavior?Solution
Step 1: Understand default value handling for query params
Query parameters come as strings or undefined. Default values should be set inside the method, not in parameter defaults.Step 2: Analyze each option
async getItems(@Query('sort') sort: string, @Query('filter') filter: string = 'all') {} tries to set default in parameter, which doesn't work well with@Query(). async getItems(@Query() query) { const filter = query.filter || 'all'; return { sort: query.sort, filter }; } extracts all query params and sets default forfilterinside method correctly. async getItems(@Query('sort') sort: string, @Query('filter') filter?: string) { if (!filter) filter = 'all'; return { sort, filter }; } tries to assign to parameter which is readonly. async getItems(@Query('sort') sort: string, @Query('filter') filter: string) { filter = filter ?? 'all'; return { sort, filter }; } assigns default after parameter, but parameter is readonly, so it causes error.Final Answer:
async getItems(@Query() query) { const filter = query.filter || 'all'; return { sort: query.sort, filter }; } -> Option AQuick Check:
Set defaults inside method body = A [OK]
- Trying to assign default values in parameter list with
@Query() - Mutating readonly parameters
- Not handling missing query params properly
Ready to prove it?
Pass the test and this pattern moves unknown
