nestjs @Param的實現(xiàn)示例
一、基礎入門:提取單個路由參數(shù)
定義路由參數(shù)
在控制器方法中,使用 :paramName 語法聲明路徑參數(shù):
import { Controller, Get, Param } from '@nestjs/common';
@Controller('users')
export class UsersController {
@Get(':id')
findOne(@Param('id') id: string) {
return `User ID: ${id}`; // 訪問 /users/123 返回 "User ID: 123"
}
}
參數(shù)類型處理
默認返回字符串類型,如需數(shù)字或其他類型,需手動轉換:
@Get(':id')
findOne(@Param('id') id: string) {
const numericId = parseInt(id, 10); // 轉為數(shù)字
return `Numeric ID: ${numericId}`;
}
二、進階技巧:批量提取與類型安全
批量提取所有參數(shù)
直接使用 @Param() 不傳參數(shù),獲取所有路由參數(shù)的鍵值對:
@Get(':userId/posts/:postId')
findPost(@Param() params: { userId: string; postId: string }) {
return `User ${params.userId}'s Post ${params.postId}`;
}
結合 DTO 實現(xiàn)類型安全
通過自定義類或接口定義參數(shù)結構:
interface RouteParams {
userId: string;
postId: string;
}
@Get(':userId/posts/:postId')
findPost(@Param() params: RouteParams) {
return `User ${params.userId}'s Post ${params.postId}`;
}
三、高級應用:參數(shù)驗證與嵌套路由
參數(shù)驗證(結合 @nestjs/validated)
使用 class-validator 和 class-transformer 驗證參數(shù):
import { IsNumberString } from 'class-validator';
class UserParams {
@IsNumberString()
id: string;
}
@Get(':id')
findOne(@Param() params: UserParams) {
// 若 id 非數(shù)字,自動返回 400 錯誤
return `Valid User ID: ${params.id}`;
}
嵌套路由中的參數(shù)提取
在模塊化路由中,參數(shù)會逐級傳遞:
// 模塊路由:/api/users/:userId/orders/:orderId
@Controller('users/:userId/orders')
export class OrdersController {
@Get(':orderId')
findOrder(
@Param('userId') userId: string,
@Param('orderId') orderId: string,
) {
return `Order ${orderId} of User ${userId}`;
}
}
四、最佳實踐:錯誤處理與性能優(yōu)化
參數(shù)缺失的默認處理
NestJS 會自動返回 404 錯誤,若需自定義響應:
@Get(':id')
findOne(@Param('id') id: string) {
if (!id) {
throw new NotFoundException('ID is required');
}
return `User ID: ${id}`;
}
性能優(yōu)化:緩存參數(shù)解析結果
對頻繁訪問的參數(shù),可在服務層緩存解析結果:
@Injectable()
export class UsersService {
private cache = new Map<string, any>();
findOne(id: string) {
if (this.cache.has(id)) {
return this.cache.get(id);
}
const user = { id, name: 'Example' }; // 模擬數(shù)據(jù)庫查詢
this.cache.set(id, user);
return user;
}
}
五、常見問題與解決方案
問題:參數(shù)未提取到
- 檢查路由路徑是否包含
:paramName。 - 確保請求 URL 與路由定義匹配(如
/users/1而非/users?id=1)。
問題:參數(shù)類型錯誤
- 顯式轉換類型(如
parseInt(id, 10))。 - 使用
class-validator進行嚴格驗證。
問題:嵌套路由參數(shù)沖突
- 避免不同層級使用相同參數(shù)名(如
/users/:id/posts/:id會沖突)。
六、完整示例:RESTful API 實現(xiàn)
import { Controller, Get, Param, Post, Body, NotFoundException } from '@nestjs/common';
interface CreateUserDto {
name: string;
email: string;
}
@Controller('users')
export class UsersController {
private users = [{ id: '1', name: 'Alice', email: 'alice@example.com' }];
@Get(':id')
findOne(@Param('id') id: string) {
const user = this.users.find(u => u.id === id);
if (!user) {
throw new NotFoundException('User not found');
}
return user;
}
@Post()
create(@Body() userData: CreateUserDto) {
const newUser = {
id: Date.now().toString(),
...userData,
};
this.users.push(newUser);
return newUser;
}
}
到此這篇關于nestjs @Param的實現(xiàn)示例的文章就介紹到這了,更多相關nestjs @Param 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
微信小程序如何根據(jù)不同用戶切換不同TabBar(簡單易懂!)
小程序中我們可能需要根據(jù)不同的權限展示不同的tabbar,下面這篇文章主要給大家介紹了關于微信小程序如何根據(jù)不同用戶切換不同TabBar的相關資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2022-04-04
js獲得指定控件輸入光標的坐標兼容IE,Chrome,火狐等多種主流瀏覽器
js獲得指定控件光標的坐標,兼容IE,Chrome,火狐等多種主流瀏覽器,實現(xiàn)代碼及調(diào)用代碼如下,感興趣的朋友可以參考下哈,希望對你有所幫助2013-05-05

